I am working on an application which requires some configuration to be stored in /etc/hosts file of a docker container. I have tried it with many options but did not find any correct way of modifying the /etc/hosts file at run time.
I want to do it either by Dockerfile or by java code. I am able to build the docker image and modify the /etc/hosts files manually, but unfortunately that is not our projects requirement.
I had the same problem and overcome it with
vi
inex
mode.ex -sc '%s/foo/bar/g|x' /etc/hosts
The recommended solution is to use the
--add-host
option todocker run
or the equivalent in thedocker-compose.yml
file if you're using docker-compose.BUT, I was in the same boat as you. I have a script that modifies the hosts file that I wanted to run in the container, so what I did was
COPY
the script into the container and make it executable, then in the Dockerfile'sCMD
script that your choose, call your script to modify the hosts fileWorks
in Dockerfile
And in the
run.sh
script I execute that script to modify the hosts fileDoesn't Work
in Dockerfile
You have to run the script that modifies your hosts file during your
CMD
script. If you run it viaRUN bash ./modifyHostsFile.sh
in your Dockerfile it will be added to that container, but then Docker will continue to the next step in the Dockerfile and create a new container (it creates a new intermediary container for each step in the Dockerfile) and your changes to the/etc/hosts
will be overridden.Depends upon what sort of modifications you want to do. If you just need to add more hosts, you can probably do it within docker run command like -
This link might be useful as well :- https://github.com/docker/docker/issues/10324