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 a3bc8d7d736f6f03e8a8678e0ff31c1c31176792d4e4374c8873e51d13a3e78b $ 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 3d1962adf47b98de71342ca87c2b56a4e8c8ecbec4191c0e0f1a3131c3a99fe4 $ 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 # env [...] NC_PORT_8080_TCP_ADDR=172.17.0.2 NC_PORT_8080_TCP_PORT=8080
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 foobar
The logs of the server container do show that the text is indeed received:
$ docker logs nc-server foobar
This simple example shows how to link two containers together. The next step is now to try this with real applications and daemons.