Generally speaking, /etc/hosts file can not be modified before running the docker container. However, current docker has an option “–add-host” which adds host-entries onto /etc/hosts when the container is run.
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 thedocker 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
docker-compose.yml
to your developers.You can not modify the host file in the image using echo
in RUN
step because docker daemon will maintain the file(/etc/hosts) and its content(hosts entry) when you start a container from the image.
However following can be used to achieve the same:
ENTRYPOINT ["/bin/sh", "-c" , "echo 192.168.254.10 database-server >> /etc/hosts && echo 192.168.239.62 redis-ms-server >> /etc/hosts && exec java -jar ./botblocker.jar " ]
Key to notice here is the use of exec
command as docker documentation suggests. Use of exec will make the java command as PID 1 for the container. Docker interrupts will only respond to that.
See https://docs.docker.com/engine/reference/builder/#entrypoint
I think docker recently added the --add-host
flag to docker build which is really great.
[Edit] So this feature was updated on 17.04.0-ce
For more detail on how to use docker build
with the --add-host
flag please visit: https://docs.docker.com/edge/engine/reference/commandline/build/
Since this still comes up as a first answer in Google I'll contribute possible solution.
Command taken from here suprisingly worked for me (Docker 1.13.1, Ubuntu 16.04) :
docker exec -u 0 <container-name> /bin/sh -c "echo '<ip> <name> >> /etc/hosts"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With