In this section, we introduce the concept of linking two containers. Docker creates a tunnel between the containers, which doesn't need to expose any ports externally on the container. It uses environment variables as one of the mechanisms for passing information from the parent container to the child container.
In addition to the environment variable env
, Docker also adds a host entry for the source container to the /etc/hosts
file. The following is an example of the host file:
$ docker run -t -i --name c2 --rm --link c1:c1alias training/webapp /bin/bash root@<container_id>:/opt/webapp# cat /etc/hosts 172.17.0.1 aed84ee21bde ... 172.17.0.2 c1alaias 6e5cdeb2d300 c1
There are two entries:
c2
that uses the Docker container ID as a host name172.17.0.2 c1alaias 6e5cdeb2d300 c1
, uses the link
alias to reference the IP address of the c1
containerThe following figure shows two containers Container 1 and Container 2 connected using veth pairs to the docker0
bridge with --icc=true
. This means these two containers can access each other through the bridge:
Links provide service discovery for Docker. They allow containers to discover and securely communicate with each other by using the flag -link name:alias
. Inter-container communication can be disabled with the daemon flag -icc=false
. With this flag set to false
, Container 1 cannot access Container 2 unless explicitly allowed via a link. This is a huge advantage for securing your containers. When two containers are linked together, Docker creates a parent-child relationship between them, as shown in the following figure:
From the outside, it looks like this:
# start the database $ sudo docker run -dp 3306:3306 --name todomvcdb -v /data/mysql:/var/lib/mysql cpswan/todomvc.mysql # start the app server $ sudo docker run -dp 4567:4567 --name todomvcapp --link todomvcdb:db cpswan/todomvc.sinatra
On the inside, it looks like this:
$ dburl = ''mysql://root:pa55Word@'' + ENV[''DB_PORT_3306_TCP_ADDR''] + ''/todomvc'' $ DataMapper.setup(:default, dburl)