1、基础知识
1.1、基础命令
]# docker network help
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network
create Create a network
disconnect Disconnect a container from a network
inspect Display detailed information on one or more networks
ls List networks
prune Remove all unused networks
rm Remove one or more networks
1.2、默认网络
]# docker network ls
NETWORK ID NAME DRIVER SCOPE
9e6261ada44a bridge bridge local
2d3c9c5ebff5 host host local
416f30bbad4f none null local
1.3、五种网络模型
1.3.1、bridge
1.3.2、host
1.3.3、container
1.3.4、none
1.3.5、overlay
1.4、命令语法
1.4.1、创建网络
docker network create --driver [网络类型] [网络名称]
1.4.2、使用网络
docker run --net=[网络名称] -itd --name=[容器名称] [镜像名称]
1.4.3、断开网络
docker network disconnect [网络名] [容器名]
1.4.4、连接网络
docker network connect [网络名] [容器名]
2、实战
2.1、创建网络
2.1.1、创建命令
docker network create --driver bridge bridge-test
2.1.2、查询创建效果
]# docker network ls
NETWORK ID NAME DRIVER SCOPE
9e6261ada44a bridge bridge local
f390d8bfd39d bridge-test bridge local
2d3c9c5ebff5 host host local
416f30bbad4f none null local
2.1.3、查看新建网络的网络信息
]# docker network inspect bridge-test
[
{
"Name": "bridge-test",
"Id": "f390d8bfd39dd747703b7aae77830152dcce64b5a5c4fba5808fa0328ec08cbc",
"Created": "2023-05-18T14:50:46.901511967+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": {},
"Config": [
{
"Subnet": "172.18.0.0/16",
"Gateway": "172.18.0.1"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {},
"Options": {},
"Labels": {}
}
]
2.1.4、宿主机又多出来一个网卡设备
]# ifconfig
br-f390d8bfd39d: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 172.18.0.1 netmask 255.255.0.0 broadcast 172.18.255.255
...
2.2、应用网络
2.2.1、容器启动时候使用网络
docker run --net=bridge-test -it -d --name=nginx-new-bri nginx
]# docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' nginx-new-bri
172.18.0.2
2.3、断开网络
docker network disconnect bridge-test nginx-new-bri
]# docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' nginx-new-bri
空
2.4、连接网络
docker network connect bridge-test nginx-new-bri
]# docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' nginx-new-bri
172.18.0.2
3、启动容器的时候,设置网络模型
docker run --network=host --rm -d nginx
docker run --network=bridge --rm -d nginx
docker run --network=null --rm -d nginx