Playing around with Docker is fun. Things get even more exciting when you start linking containers together. This can easily be tested with the help of Netcat.
First of all, make sure that you have an image with Netcat installed. In this example the basic centos image is used, but really any Linux image like Ubuntu, Debian and so on should be fine as long as the package manager provides Netcat.
A Centos image with Netcat installed is created and commited with the name “nc”:
$ docker run -t centos yum -y install nc
$ docker ps -a
CONTAINER ID IMAGE COMMAND ...
69d6c32dd258 centos:centos6 yum -y install nc ...
$ docker commit 69d6c32dd258 nc-image
$ docker images
REPOSITORY TAG IMAGE ID ...
nc-image latest a3bc8d7d736f ...
To test linking we now set up the server container with
nc listening on port 8080:
$ docker run -d -p 8080 --name nc-server nc-image nc -l 8080
$ docker ps
... STATUS PORTS NAMES
... Up 6 seconds 0.0.0.0:49155->8080/tcp nc-server
As can be seen above the
ps command also shows the port forwarding.
The link can now be created by starting another container and telling Docker in the
run command that it should be linked to the “server”. In this example the container is run interactively with
/bin/bash to show how the connection is seen from inside the “client” container: Docker defines a set of environment variables to tell the container how ports on other containers can be reached.
$ docker run -i -t --rm=true --name nc-client --link nc-server:nc nc-image /bin/bash
At the same time, the Docker process monitor
docker ps now shows that these containers are linked:
... COMMAND ... PORTS NAMES
... /bin/bash ... nc-client
... nc -l 8080 ... 0.0.0.0:49155->8080/tcp nc-client/nc,nc-server
The client container can now talk to directly to the port of the server container. Inside the client container we call nc on the specific port:
bash-4.1# nc 172.17.0.2 8080
The logs of the server container do show that the text is indeed received:
$ docker logs nc-server
This simple example shows how to link two containers together. The next step is now to try this with real applications and daemons.