Local hostnames for Docker containers

OK,

so since it seems that there is no native way to do this with Docker, I finally opted for this alternate solution from Ryan Armstrong, which consists in dynamically updating the /etc/hosts file.

I chose this since it was convenient for me since this works as a script, and I already had a startup script, so I could just append this function in to it.

The following example creates a hosts entry named docker.local which will resolve to your docker-machine IP:

update-docker-host(){
    # clear existing docker.local entry from /etc/hosts
    sudo sed -i '' '/[[:space:]]docker\.local$/d' /etc/hosts

    # get ip of running machine
    export DOCKER_IP="$(echo ${DOCKER_HOST} | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')"

    # update /etc/hosts with docker machine ip
    [[ -n $DOCKER_IP ]] && sudo /bin/bash -c "echo \"${DOCKER_IP}   docker.local\" >> /etc/hosts"
}

update-docker-host

This will automatically add or udpate the /etc/hosts line on my host OS when I start the Docker machine through my startup script.

Anyways, as I found out during my research, apart from editing the hosts file, you could also solve this problem by setting up a custom DNS server:

Also found several projects on Github which apparently aim to solve this problem, although I didn't try them:

  • https://github.com/jpetazzo/pipework
  • https://github.com/bnfinet/docker-dns
  • https://github.com/gliderlabs/resolvable

Extending on @eduwass's own answer, here's what I did manually (without a script).

  1. As mentioned in the question, define the domainname: myapp.dev and hostname: www in the docker-compose.yml file
  2. Bring up your Docker containers as normal
  3. Run docker-compose exec client cat /etc/hosts to get an output of the container's hosts file (where client is your service name) (Output example: 172.18.0.6 www.myapp.dev)
  4. Open your local (host machine) /etc/hosts file and add that line: 172.18.0.6 server.server.dev

If your Docker service container changes IPs or does anything fancy you will want a more complex solution, but this is working for my simple needs at the moment.