Docker container linking

Docker container linking

Linking Docker containers can be done in various ways. In my recent attempt of playing with Docker and our GitLab Review Apps setup, I experimented with different methods to figure out what would work best. These are the different options I played around with:

1. The low-level method

As you might know `docker inspect` can give you a ton of information on how a specific container is configured. Parsing the JSON response of docker inspect is surely possible but not needed. As it turns out you are able to query certain parts of the docker inspect output, like the IP address of the container. All you need to run a command like this:

docker inspect -f
'{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'

This will just return the configured IP address. You can use the return value of the above command when configuring environment variables of your container:

docker run -d -P
-e ENDPOINT=$(docker inspect -f '{{range .NetworkSettings.Networks}}
  {{.IPAddress}}{{end}}' the-container-to-link) 
--name app-container some/image:latest

If you really need the IP address and not a hostname for some reason this seems be a suitable approach.

2. Linking by name

You can link containers by passing the --link argument to the docker run command:

docker run -d -P -e ENDPOINT=the-container-to-link 
--link the-container-to-link --name app-container some/image:latest

3. docker-compose

You can define a separate docker-compose file `` like the one below:

version: "2"
    image: some/image:latest
    image: the-container-to-link:latest

And then run it via:

docker-compose -f

Whilst the docker-compose version seems to be the simplest solution I still prefer the "linking by name" variant in our GitLab CI setup as this is one file less to maintain.

Tags: , ,

Eintrag von Stephan Hochdörfer am 08.08.2017

comments powered by Disqus