Docker Linking

Quick into to Docker’s automagic container linking. If you’re running on a single host and need containers to talk to each other, then this is worth a look.

Firstly, you’ll need a Docker file which lists the ports you want to expose

# A simple base image which exposes some ports and a mountable volume
FROM centos:latest
MAINTAINER Andrew Gorton <[email protected]>
 
RUN mkdir -p /mnt/data
 
EXPOSE 80
EXPOSE 443
 
VOLUME ["/mnt/data"]
 
CMD ["/bin/bash", "-l"]

RUN mkdir -p /mnt/data

EXPOSE 80
EXPOSE 443

VOLUME ["/mnt/data"]

CMD ["/bin/bash", "-l"]

Save this file as Dockerfile.sharer. This is a simple machine which exposes ports 80 and 443, and a volume. It also declares the default entry point to be a Bash shell.

Build it with

docker build -t andrewgorton/basic-sharer - < Dockerfile.sharer

Run it as a named container with

docker run -it --name sharer andrewgorton/basic-sharer

Now create a container which links to it

docker run -it  --link sharer:sharer --volumes-from sharer centos:latest /bin/bash -l

This populates this consuming container with

bash-4.2# env | sort
SHARER_NAME=/hungry_lalande/sharer
SHARER_PORT=tcp://172.17.0.16:80
SHARER_PORT_443_TCP=tcp://172.17.0.16:443
SHARER_PORT_443_TCP_ADDR=172.17.0.16
SHARER_PORT_443_TCP_PORT=443
SHARER_PORT_443_TCP_PROTO=tcp
SHARER_PORT_80_TCP=tcp://172.17.0.16:80
SHARER_PORT_80_TCP_ADDR=172.17.0.16
SHARER_PORT_80_TCP_PORT=80
SHARER_PORT_80_TCP_PROTO=tcp
 
bash-4.2# cat /etc/hosts
172.17.0.11	sharer
 
bash-4.2# mount
/dev/sda1 on /mnt/data type ext4 (rw,relatime,data=ordered)

bash-4.2# cat /etc/hosts
172.17.0.11 sharer

bash-4.2# mount
/dev/sda1 on /mnt/data type ext4 (rw,relatime,data=ordered)

so you can see a bunch of environment variables detailing the exposed ports, and the hosts file has an entry for ‘sharer’. It also mounted the exposed volume so any file changes under /mnt/data actually happen in the ‘sharer’ container (see the Data Volume Container docs for more information).

This doesn’t work if you’re running the containers on separate hosts. Docker is working on Ambassadors for this, but in the meantime you might want to look at Weave.

This is my personal blog - all views are my own.

Tagged with: , ,