How to update /etc/hosts file in Docker image during "docker build"

Prakash picture Prakash · Jul 11, 2016 · Viewed 142.1k times · Source

I want to update my /etc/hosts file during "docker build".

I added below line in Dockerfile but it's neither updating /etc/hosts file nor giving any error.

RUN echo "192.168.33.11    mynginx" >> /etc/hosts

I need to update /etc/hosts. Can anyone suggest on this?

Answer

VonC picture VonC · Jul 11, 2016

With a more recent version of docker, this could be done with docker-compose and its extra_hosts directive

Add hostname mappings.
Use the same values as the docker run client --add-host parameter (which should already be available for docker 1.8).

extra_hosts:
 - "somehost:162.242.195.82"
 - "otherhost:50.31.209.229"

In short: modify /etc/hosts of your container when running it, instead of when building it.


With Docker 17.x+, you have a docker build --add-host mentioned below, but, as commented in issue 34078 and in this answer:

The --add-host feature during build is designed to allow overriding a host during build, but not to persist that configuration in the image.

The solutions mentioned do refer the docker-compose I was suggesting above:

  • Run an internal DNS; you can set the default DNS server to use in the daemon; that way every container started will automatically use the configured DNS by default
  • Use docker compose and provide a docker-compose.yml to your developers.
    The docker compose file allows you to specify all the options that should be used when starting a container, so developers could just docker compose up to start the container with all the options they need to set.