docker的link是通过使用容器的ip地址来实现多容器之间通信的。关于link在宿主主机网络上的实现原理不在这里介绍。
link格式
sudo docker run -ti --link container:alias images
测试
由于redis天然的c/s结构和较小的体积,暂用redis测试
下载redis镜像
suntopo@suntopo-X550VX:~$ sudo docker pull redis
创建redis容器
suntopo@suntopo-X550VX:~$ sudo docker run --name redis-server -d redis
bc569786abd83513f89fbe7f7fbfbd2198032337d08b995382d1abe180a2036e
suntopo@suntopo-X550VX:~$ sudo docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
bc569786abd8 redis "docker-entrypoint.sh" 25 seconds ago Up 24 seconds 6379/tcp redis-server
254938ab2e20 0d1cbfaa41da "docker-entrypoint.sh" 4 weeks ago Exited (0) 6 days ago zen_murdock
0a1a11d5263b mongo "/entrypoint.sh mongo" 5 weeks ago Exited (0) 13 days ago berserk_ride
进入redis容器
suntopo@suntopo-X550VX:~$ sudo docker exec -it redis-server /bin/bash
root@bc569786abd8:/data# redis-cli
127.0.0.1:6379> set name suntopo
OK
127.0.0.1:6379> get name
"suntopo"
127.0.0.1:6379>
使用link连接容器
suntopo@suntopo-X550VX:~$ sudo docker run -ti --link redis-server:redis-server redis /bin/bash
root@a032da74b250:/data# env
REDIS_SERVER_ENV_REDIS_VERSION=3.2.4
HOSTNAME=a032da74b250
REDIS_SERVER_PORT_6379_TCP_PORT=6379
REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-3.2.4.tar.gz
TERM=xterm
REDIS_SERVER_PORT_6379_TCP_PROTO=tcp
REDIS_SERVER_ENV_REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-3.2.4.tar.gz
REDIS_SERVER_PORT=tcp://172.17.0.2:6379
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
REDIS_SERVER_ENV_REDIS_DOWNLOAD_SHA1=f0fe685cbfdb8c2d8c74613ad8a5a5f33fba40c9
PWD=/data
REDIS_SERVER_ENV_GOSU_VERSION=1.7
SHLVL=1
HOME=/root
REDIS_VERSION=3.2.4
REDIS_DOWNLOAD_SHA1=f0fe685cbfdb8c2d8c74613ad8a5a5f33fba40c9
REDIS_SERVER_PORT_6379_TCP=tcp://172.17.0.2:6379
REDIS_SERVER_NAME=/evil_fermat/redis-server
GOSU_VERSION=1.7
REDIS_SERVER_PORT_6379_TCP_ADDR=172.17.0.2
_=/usr/bin/env
root@a032da74b250:/data# ^C
root@a032da74b250:/data# redis-cli -h $REDIS_SERVER_PORT_6379_TCP_ADDR
172.17.0.2:6379> get name
"suntopo"
172.17.0.2:6379>
注: 环境变量的前缀就是用alias大写命名的。