Local hostnames for Docker containers

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)