--linkflag which allows to connect any number of docker containers without the need to expose container's internal ports to the outside world.
In this config you will learn how to link two or more docker containers together using a simple docker networking technique. We can start by the deployment of our first docker container
sanbox1to which we'll later create a network link:
# docker run -it --name sandbox1 -h sanbox1 linuxconfig/sandbox /bin/bashThere is nothing new about the above command except to note that we are not exposing any network ports even though our intention is to access services ( ssh, database etc.) via their relevant port numbers.
The following linux command will deploy a second and this time a parent docker container named
sandbox2. We will also use a
--linkflag which will create a so called parent-child relationship with previously deployed container
--linkflag will enable the parent container to access any services running on
sandbox1container via its corresponding ports numbers without the child container's need to expose any ports to outside world.
# docker run -it --name sandbox2 -h sandbox2 --link sandbox1:sandbox1 linuxconfig/sandbox /bin/bashThe above docker command used
--linkflag which expects two arguments separated by column. The first argument is expected to be a container ID or as in our case a supplied
sandbox1container name we would like to link to. The second argument
sandbox1is an internal alias used by
sandbox1's network configuration using
# grep sandbox1 /etc/hosts 172.17.0.41 sandbox1
sandbox1's configuration from system environment variables eg.:
# env HOSTNAME=sandbox2 TERM=xterm SANDBOX1_PORT=tcp://172.17.0.37:7555 SANDBOX1_PORT_7555_TCP=tcp://172.17.0.37:7555 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PWD=/ SANDBOX1_PORT_7555_TCP_ADDR=172.17.0.37 SANDBOX1_PORT_7555_TCP_PROTO=tcp SHLVL=1 HOME=/root SANDBOX1_NAME=/sandbox2/sandbox1 SANDBOX1_PORT_7555_TCP_PORT=7555 _=/usr/bin/envThis way we can simply use our child container's alias to connect to it from a parent container
sandbox2without the need to hardcode it's IP address:
# ping -c 1 sandbox1 PING sandbox1 (172.17.0.41): 56 data bytes 64 bytes from 172.17.0.41: icmp_seq=0 ttl=64 time=0.071 ms --- sandbox1 ping statistics --- 1 packets transmitted, 1 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.071/0.071/0.071/0.000 msand also access any ports ports and services:
# nmap -p 22 sandbox1 Starting Nmap 6.47 ( http://nmap.org ) at 2015-05-18 08:58 UTC Nmap scan report for sandbox1 (172.17.0.41) Host is up (0.000090s latency). PORT STATE SERVICE 22/tcp open ssh MAC Address: 02:42:AC:11:00:29 (Unknown) Nmap done: 1 IP address (1 host up) scanned in 0.50 seconds