How to update /etc/hosts file in Docker image duri

2019-03-09 06:07发布

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?

7条回答
爷的心禁止访问
2楼-- · 2019-03-09 06:48

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, not building it.

查看更多
在下西门庆
3楼-- · 2019-03-09 06:49

Following worked for me by mounting the file during docker run instead of docker build

docker service create --name <name>  --mount type=bind,source=/etc/hosts,dst=/etc/hosts   <image>
查看更多
孤傲高冷的网名
4楼-- · 2019-03-09 06:55

Just a quick answer to run your container using:

docker exec -it <container name> /bin/bash

once the container is open:

cd ..

then

`cd etc`

and then you can

cat hosts

or:

apt-get update
apt-get vim

or any editor you like and open it in vim, here you can modify say your startup ip to 0.0.0.0

查看更多
Explosion°爆炸
5楼-- · 2019-03-09 06:57

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"
查看更多
唯我独甜
6楼-- · 2019-03-09 06:58

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/

查看更多
看我几分像从前
7楼-- · 2019-03-09 07:00

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

查看更多
登录 后发表回答