docker的link是經過使用容器的ip地址來實現多容器之間通訊的。關於link在宿主主機網絡上的實現原理不在這裏介紹。redis
sudo docker run -ti --link container:alias images
因爲redis自然的c/s結構和較小的體積,暫用redis測試docker
下載redis鏡像bash
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容器tcp
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鏈接容器ide
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大寫命名的。測試