Docker 容器间的互联
指尖二进制 • 1 年前 • 757 次点击 • DOCKER
(--link 是单方向的!!!)
[root@docker-01 ~]# docker run -itd --name web01 nginx:latest
[root@docker-01 ~]# docker run -itd centos6_9_ssh_nginx:v1 /bin/bash
[root@docker-01 ~]# docker ps
CONTAINER ID
f58bd323e6e3
[root@docker-01 ~]# docker exec -it f58bd323e6e3 /bin/bash
[root@f58bd323e6e3 /]# ping 172.17.0.2 -c2 #默认容器和容器之间是能够相互通信的
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.063 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.048 ms
[root@f58bd323e6e3 /]# ping 172.17.0.1 -c2
PING 172.17.0.1 (172.17.0.1) 56(84) bytes of data.
64 bytes from 172.17.0.1: icmp_seq=1 ttl=64 time=0.062 ms
64 bytes from 172.17.0.1: icmp_seq=2 ttl=64 time=0.042 ms
那么这个时候怎么启动一个容器去直接访问web01容器
[root@docker-01 ~]# docker run -itd --name testweb01 --link web01:web01 centos6_9_ssh_nginx:v1 /bin/bash
[root@docker-01 ~]# docker exec -it testweb01 /bin/bash
[root@6fa01dc8c627 /]# ping web01 -c2
PING web01 (172.17.0.2) 56(84) bytes of data.
64 bytes from web01 (172.17.0.2): icmp_seq=1 ttl=64 time=0.111 ms
64 bytes from web01 (172.17.0.2): icmp_seq=2 ttl=64 time=0.047 ms
[root@6fa01dc8c627 /]# curl -I web01
HTTP/1.1 200 OK
Server: nginx/1.17.9
Date: Fri, 27 Mar 2020 10:25:21 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 03 Mar 2020 14:32:47 GMT
Connection: keep-alive
ETag: "5e5e6a8f-264"
Accept-Ranges: bytes
--link实现原理:把--link的web01ip地址、容器名字、容器id写入到testweb01容器hosts解析里面
[root@6fa01dc8c627 /]# cat /etc/hosts
172.17.0.2 web01 3eb92dc5edc4
[root@docker-01 ~]# docker ps -a|grep 3eb92dc5edc4
3eb92dc5edc4 nginx:latest "nginx -g 'daemon of…" 7 minutes ago Up 7 minutes 80/tcp web01