文章来源于Docker 官网:https://docs.docker.com/engine/tutorials/networkingcontainers/
,这里做一个学习后的总结。
Docker 通过网卡搭建容器之间的网络连接,Docker的网卡驱动分为两种 bridge
和 overlay
Docker 默认有一个名为bridge的网卡,如果不指定网卡,container默认是在这张网卡上启动的。
docker network ls
NETWORK ID NAME DRIVER SCOPE
b033b76b5539 bridge bridge local
通过下面这条信息可以查看使用bridge网卡的容器(查看Containers 字段)。
$ docker network inspect bridge
[
{
"Name": "bridge",
"Id": "f7ab26d71dbd6f557852c7156ae0574bbf62c42f539b50c8ebde0f728a253b6f",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.17.0.1/16",
"Gateway": "172.17.0.1"
}
]
},
"Internal": false,
"Containers": {
"3386a527aa08b37ea9232cbcace2d2458d49f44bb05a6b775fba7ddd40d8f92c": {
"Name": "networktest",
"EndpointID": "647c12443e91faf0fd508b6edfe59c30b642abb60dfab890b4bdccee38750bc1",
"MacAddress": "02:42:ac:11:00:02",
"IPv4Address": "172.17.0.2/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": "9001"
},
"Labels": {}
}
]
构建自己的bridge network
- 创建bridge1 网卡
docker network create -d bridge my_bridge1
c068f1c8e65ecaa8e281fdf7b59c7e1cfb591775581153b022c6725ccc5d9a15
通过docker network ls
命令可以看到新增的my_bridge1网卡。
docker network ls
NETWORK ID NAME DRIVER SCOPE
b033b76b5539 bridge bridge local
527609ca342a docker_gwbridge bridge local
2c3db48046d6 host host local
af7ad5a2fdad my_bridge bridge local
c068f1c8e65e my_bridge1 bridge local
0c576048b52e none null local
在my_bridge1 网卡上运行postgres 数据库container
docker run -d --net=my_bridge1 --name db training/postgres
运行web服务器,但是不指定网卡(没有-net参数)
docker run -d --name web training/webapp python app.py
获取web container的ip地址。
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' web
为:172.17.0.2
进入到数据库的bash中:docker exec -it db bash
在里面ping web的IP地址172.17.0.2
,这时候是ping不通的。
root@170a75e0cabe:/# ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
^C
--- 172.17.0.2 ping statistics ---
22 packets transmitted, 0 received, 100% packet loss, time 21293ms
指定web container使用my_bridge1网卡。
dockedocker network connect my_bridge1 web
在db container中在ping web container的ip,是可以ping通的。
# docker exec -it db bash
root@170a75e0cabe:/# ping web
PING web (172.20.0.3) 56(84) bytes of data.
64 bytes from web.my_bridge1 (172.20.0.3): icmp_seq=1 ttl=64 time=0.086 ms
64 bytes from web.my_bridge1 (172.20.0.3): icmp_seq=2 ttl=64 time=0.069 ms
64 bytes from web.my_bridge1 (172.20.0.3): icmp_seq=3 ttl=64 time=0.074 ms
简单的总结一下流程是:
创建一张桥接网卡 mybridge1 ,在创建db 和 web容器时指定使用这张网卡就可以实现两个容器的网络互通了。