使用 –link 参数可以让容器之间安全的进行交互
[root@redis ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hub.c.163.com/public/redis 2.8.4 4888527e1254 13 months ago 190.4 MB
hub.c.163.com/public/nginx 1.2.1 2dc68ff797db 18 months ago 171.5 MB
新建一个容器 redis
[root@redis ~]# docker run -d --name redis 488
adde428a0a39627cc5134b9313cc0746f3551794ccb7c57b04fa816fddba7131
新建一个容器 app
[root@redis ~]# docker run -d –name app –link db:db 2dc
f44ad0a211ea2f20433d101c78840562c8f79ca675c80048965459dd0bbd7a68
–link 参数的格式为 –link name:alias,其中 name 是要连接的容器名称,alias 是连接的别名。
查看进程
[root@redis ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f44ad0a211ea 2dc "/bin/sh -c '/etc/ini" 3 seconds ago Up 2 seconds 22/tcp, 80/tcp, 443/tcp app
e918789d6aee 488 "/run.sh" About a minute ago Up About a minute 6379/tcp db
查看 hosts 文件会发现有db 的 ip 是172.17.0.2
[root@redis ~]# docker exec -it f44 /bin/bash
root@f44ad0a211ea:/# cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2 db e918789d6aee
172.17.0.3 f44ad0a211ea
ping 下试试
root@f44ad0a211ea:/# ping db
PING db (172.17.0.2) 56(84) bytes of data.
64 bytes from db (172.17.0.2): icmp_req=1 ttl=64 time=0.107 ms
64 bytes from db (172.17.0.2): icmp_req=2 ttl=64 time=0.080 ms
64 bytes from db (172.17.0.2): icmp_req=3 ttl=64 time=0.100 ms
^C
--- db ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1999ms
rtt min/avg/max/mdev = 0.080/0.095/0.107/0.016 ms
Telnet db 的端口
root@f44ad0a211ea:/# telnet 172.17.0.2 6379
Trying 172.17.0.2...
Connected to 172.17.0.2.
Escape character is '^]'.