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:
# /etc/hosts.tmpl
127.0.0.1 localhost{{ range $container := $ }}
{{- $address := first $container.Addresses -}}
{{- $network := first $container.Networks -}} {{- if $address.IP -}}
{{- $address.IP -}}
{{- else -}}
{{- $network.IP -}}
{{- end -}} {{- " " -}}{{- $container.Name -}}.local {{- if contains $container.Labels "com.docker.compose.project" -}}
{{- " " }}{{ index $container.Labels "com.docker.compose.service" }}.{{ index $container.Labels "com.docker.compose.project" }}.local
{{- end }}
{{ end }}
With this template, each container will be associated with the following domains names:
{containerName}.local
- If the container was created by
docker-compose
:{serviceName}.{projectName}.local
Then we create a docker-gen configuration file:
# docker-gen.cfg
[[config]]dest = "/etc/hosts"
template = "/etc/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.local
URL.