Docker container management

At theTribe we use docker to easily create development environments. It’s nice: you clone the project, launch docker-compose and you can start coding.

But when you work on multiple projects at the same time it starts to become hard managing all your running containers. Either you have to map each container to a different port (but then you have to remember which port each project uses) or you can directly connect to the IP of the container. But it’s the same problem: you have to remember which IP is used by the container you want to access.

Docker-gen to the rescue

Docker-gen is a tool that allows to keep files on your system up to date with a template based on the running containers. To do this docker-gen listens to events emitted by the Docker service and regenerates the files when needed.

This looks like an useful tool, let’s use it to simplify the way we find our containers.

Associating domain names with our containers

What I do is using a template file that updates my /etc/hosts file to associate some domains to my containers IPs:

# hosts.tmpl localhost

{{ range $container := $ }}
    {{- with $address := first $container.Addresses -}}
        {{- $address.IP }} {{ $container.Name }}.localhost

        {{- if contains $container.Labels "com.docker.compose.project" -}}
            {{- " " }}{{ index $container.Labels "com.docker.compose.service" }}.{{ index $container.Labels "com.docker.compose.project" }}.localhost
        {{- end -}}
    {{- end }}
{{ end }}

With this template, each container will be associated with the following domains names:

  • {containerName}.localhost
  • If the container was created by docker-compose: {serviceName}.{projectName}.localhost

Then we create a docker-gen configuration file:

# docker-gen.cfg

dest = "/etc/hosts"
template = "/path/to/hosts.tmpl"
watch = true

And start docker-gen with docker-gen -config /path/to/docker-gen.cfg

With this, accessing the “nginx” container of the project “project” can be done by simply going to the nginx.project.localhost URL.

Jérôme Vasseur

Code shaman

Nantes, France thetribe.io