容器互联
通过docker run
命令的--link
参数可以让容器之间通过连接(linking)系统进行交互。
--link name:alias
,name是要链接的容器名称, alias是此连接的别名。 容器的连接系统会依据容器的名称,创建容器之间一个安全隧道,在启动容器的时候不使用-p
和-P
参数(不用映射端口到宿主主机),从而避免了暴露端口到外部网络。
通过docker run
命令的--name
参数来自定义容器名称(容器的名称是唯一的)。
docker ps
命令结果的NAMES部分,查看容器名称。 Docker通过环境变量为容器公开连接信息,还添加host信息到父容器的/etc/hosts
文件。
示例
[root@CentOS-7 ~]# docker run -d --name nginx-node nginxfc94ef26e3ab354db09323037f9a5119b18b48b8ca8c0f353ce3d3408230456d[root@CentOS-7 ~]# [root@CentOS-7 ~]# docker run -itd --name centos-node --link nginx-node:samplelink centosb5f56401c44d7b41f060e603b0a98309a0e996ffa66a0c177edee13364820f57[root@CentOS-7 ~]# [root@CentOS-7 ~]# docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESb5f56401c44d centos "/bin/bash" 4 seconds ago Up 3 seconds centos-nodefc94ef26e3ab nginx "nginx -g 'daemon off" 23 seconds ago Up 22 seconds 80/tcp, 443/tcp nginx-node[root@CentOS-7 ~]# [root@CentOS-7 ~]# docker inspect --format "{ { .NetworkSettings.IPAddress }}" nginx-node172.17.0.2[root@CentOS-7 ~]# [root@CentOS-7 ~]# docker inspect --format "{ { .NetworkSettings.IPAddress }}" centos-node172.17.0.3[root@CentOS-7 ~]# [root@CentOS-7 ~]# docker exec -it nginx-node envPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binHOSTNAME=fc94ef26e3abNGINX_VERSION=1.11.13-1~jessieHOME=/root[root@CentOS-7 ~]# [root@CentOS-7 ~]# docker exec -it centos-node envPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binHOSTNAME=b5f56401c44dTERM=xtermSAMPLELINK_PORT=tcp://172.17.0.2:80SAMPLELINK_PORT_80_TCP=tcp://172.17.0.2:80SAMPLELINK_PORT_80_TCP_ADDR=172.17.0.2SAMPLELINK_PORT_80_TCP_PORT=80SAMPLELINK_PORT_80_TCP_PROTO=tcpSAMPLELINK_PORT_443_TCP=tcp://172.17.0.2:443SAMPLELINK_PORT_443_TCP_ADDR=172.17.0.2SAMPLELINK_PORT_443_TCP_PORT=443SAMPLELINK_PORT_443_TCP_PROTO=tcpSAMPLELINK_NAME=/centos-node/samplelinkSAMPLELINK_ENV_NGINX_VERSION=1.11.13-1~jessieHOME=/root[root@CentOS-7 ~]# [root@CentOS-7 ~]# docker exec -it nginx-node cat /etc/hosts127.0.0.1 localhost::1 localhost ip6-localhost ip6-loopbackfe00::0 ip6-localnetff00::0 ip6-mcastprefixff02::1 ip6-allnodesff02::2 ip6-allrouters172.17.0.2 fc94ef26e3ab[root@CentOS-7 ~]# [root@CentOS-7 ~]# docker exec -it centos-node cat /etc/hosts127.0.0.1 localhost::1 localhost ip6-localhost ip6-loopbackfe00::0 ip6-localnetff00::0 ip6-mcastprefixff02::1 ip6-allnodesff02::2 ip6-allrouters172.17.0.2 samplelink fc94ef26e3ab nginx-node172.17.0.3 b5f56401c44d[root@CentOS-7 ~]# [root@CentOS-7 ~]# docker exec -it centos-node ping nginx-nodePING samplelink (172.17.0.2) 56(84) bytes of data.64 bytes from samplelink (172.17.0.2): icmp_seq=1 ttl=64 time=0.339 ms64 bytes from samplelink (172.17.0.2): icmp_seq=2 ttl=64 time=0.146 ms^C--- samplelink ping statistics ---2 packets transmitted, 2 received, 0% packet loss, time 1000msrtt min/avg/max/mdev = 0.146/0.242/0.339/0.097 ms[root@CentOS-7 ~]#