Reference article: Docker modify the hosts
Why modify the hosts file directly within Docker containers are not recommended?
actually not stored in the hosts file Docker in the mirror, / etc / hosts, /etc/resolv.conf and / etc / hostname, the presence / var / lib / docker / containers / directory (docker_id) on the host, the container when you start to mount by mount these files into the interior of the container. If a change in these files in the container, modifying portion does not exist in the container top layer, but directly written in three files. There is no reason to modify the contents of the container after the restart when Docker every time you create a new container, it will re-establish the hosts file based on IP information for all nodes in the current docker0. In other words, your changes will be Docker to automatically overwritten.
How to efficiently set up hosts to Docker containers?
When you start a container, add parameters
Open container when adding parameters -add-host machine: ip hosts modification can be achieved
docker run -it --name alpine-test1 --add-host=test.baidu.com:192.168.1.37 docker.io/alpine
Modify the DockerFile
RUN mkdir /data
COPY run.sh /data/
RUN chmod +x /data/run.sh
ENTRYPOINT /bin/sh -c /data/run.sh
run.sh reads as follows:
# 向hosts文件追加内容
#cat /data/myhosts >> /etc/hosts
echo "192.168.1.37 testgitlab.kuaidihelp.com" >> /etc/hosts
# 其他命令
# 保留终端,防止容器自动退出
/bin/sh