Docker 容器之间互联

使用 –link 参数可以让容器之间安全的进行交互

[root@redis ~]# docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE   2.8.4               4888527e1254        13 months ago       190.4 MB   1.2.1               2dc68ff797db        18 months ago       171.5 MB

新建一个容器 redis

[root@redis ~]# docker run -d --name redis 488

新建一个容器 app

[root@redis ~]# docker run -d –name app –link db:db 2dc

–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                 "/"                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    localhost
::1    localhost ip6-localhost ip6-loopback
fe00::0    ip6-localnet
ff00::0    ip6-mcastprefix
ff02::1    ip6-allnodes
ff02::2    ip6-allrouters    db e918789d6aee    f44ad0a211ea

ping 下试试

root@f44ad0a211ea:/# ping db
PING db ( 56(84) bytes of data.
64 bytes from db ( icmp_req=1 ttl=64 time=0.107 ms
64 bytes from db ( icmp_req=2 ttl=64 time=0.080 ms
64 bytes from db ( icmp_req=3 ttl=64 time=0.100 ms
--- 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 6379
Connected to
Escape character is '^]'.