docker之网络与数据管理
docker默认使用bridge(单主机互联)和overlay(可跨主机互联)两种网络驱动来进行容器的网络管理。如需要,还可以自定义网络驱动插件进行docker容器的网络管理。
1.docker默认网络管理
docker network ls NETWORK ID NAME DRIVER SCOPE 506aad38ec3f bridge bridge local 8899107f108e host host local 66b732b380f4 none null local
默认有三种网络: bridge, host , none. 其中bridge 为默认网络
通过命令可以查看某个网络详情:
docker network inspect bridge [ { "Name": "bridge", "Id": "506aad38ec3fdc288a6511fa1c45a3e4d2766870387686bf9dc4cc931cf5a4c0", "Created": "2020-03-18T21:38:44.88031526+08:00", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "172.17.0.0/16", "Gateway": "172.17.0.1" } ] }, "Internal": false, "Attachable": false, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": { "39454581b2715b3c1d6b008a7e5d285639680dad733ff5f51d5d36d92bfcfaab": { "Name": "networktest", "EndpointID": "b414391ba09c65aa25fcf163c5052935fe20c5cff33a21d3cb0f5eeb12760160", "MacAddress": "02:42:ac:11:00:05", "IPv4Address": "172.17.0.5/16", "IPv6Address": "" }, "ab20a6613ae63779276f615e7137631934ca478242fdb4dca1bf5904ba6915af": { "Name": "mongo-server2", "EndpointID": "682a9bf282799993e3d9ba42e405a96032e1a240c4514b8e0346d7c2e981dec3", "MacAddress": "02:42:ac:11:00:02", "IPv4Address": "172.17.0.2/16", "IPv6Address": "" }, "ccd33e6df12a4510e9137296c3ce7ed5f179420847a2b0bcde88a6777689298c": { "Name": "docker-web2", "EndpointID": "7b0092927482eeaf0fe2b4ca3ce9818931157df88fad28eef67db9d77b918858", "MacAddress": "02:42:ac:11:00:04", "IPv4Address": "172.17.0.4/16", "IPv6Address": "" }, "df8652b3315ce415634d8001d39a8085c11df0f23b81df6ca8bab7dd5c8a6002": { "Name": "jzl0", "EndpointID": "bc0da902076813ae0c49fd400b3a89372fb37619b9a7eb949b23ada29c9ac676", "MacAddress": "02:42:ac:11:00:03", "IPv4Address": "172.17.0.3/16", "IPv6Address": "" } }, "Options": { "com.docker.network.bridge.default_bridge": "true", "com.docker.network.bridge.enable_icc": "true", "com.docker.network.bridge.enable_ip_masquerade": "true", "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0", "com.docker.network.bridge.name": "docker0", "com.docker.network.driver.mtu": "1500" }, "Labels": {} } ]
注意点:这里的bridge,host,none都是在非集群环境下,而在docker swarm集群环境中,还会有docker_gwbridge 和 ingress两种默认网络
2. 自定义bridge网络
创建网络
docker network create --driver bridge nw 说明: --driver (简写 -d) 指定网络驱动类型 nw. 创建的网路名称 --driver 可以省略 默认创建该类型的网络 创建完成,查看 docker network ls
3. 使用自定义网络启动容器
docker run -itd --network=isolated_nw --name=nwtest busybody
可以通过命令查看容器网络详情
docker inspect nwtest
4. 为容器添加其他网络管理方式
docker network connect isolated_nw busybody
指定连接的网络isolated_nw
5. 断开网络连接
docker network disconnect isolated_nw busybody
注意:一个容器可以连接多个网络,当断开全部网络连接,虽然容器在运行,但是内部的应用无法被外界访问到
6. 移除网络
docker network rm isolated_nw
容器之间的通信必须是在同一个网络中才可以,否则无法进行通信。
可以通过在容器中使用ping -w 4 其他容器IP的方式进行验证