且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在正在运行的Docker容器中编辑/ etc / hosts文件

更新时间:2023-11-25 19:59:34

推荐的解决方案是将-add-host 选项用于 docker run 或如果您使用的是docker-compose,则在 docker-compose.yml 文件中等效。

The recommended solution is to use the --add-host option to docker run or the equivalent in the docker-compose.yml file if you're using docker-compose.

但是,跟你在同一条船上我有一个脚本可以修改要在容器中运行的hosts文件,所以我要做的是将脚本 COPY 放入容器并使其可执行,然后在您选择的Dockerfile的 CMD 脚本,调用您的脚本来修改主机文件

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's CMD script that your choose, call your script to modify the hosts file

在Dockerfile中

in Dockerfile

# add the modifyHostsFile script, make it executable
COPY ./bash-scripts/modifyHostsFile.sh /home/user/modifyHostsFile.sh
RUN sudo chmod +x /home/user/modifyHostsFile.sh


# run the script that starts services
CMD ["/bin/bash", "/home/user/run.sh"]

然后在 run.sh 脚本中执行该脚本以修改主机文件

And in the run.sh script I execute that script to modify the hosts file

# modify the hosts file
bash ./modifyHostsFile.sh



不起作用在Dockerfile中

Doesn't Work

in Dockerfile

# add the modifyHostsFile script, make it executable
COPY ./bash-scripts/modifyHostsFile.sh /home/user/modifyHostsFile.sh
RUN sudo chmod +x /home/user/modifyHostsFile.sh

# modify the hosts file right now
RUN bash /home/user/modifyHostsFile.sh    

# run the script that starts services
CMD ["/bin/bash", "/home/user/run.sh"]






您有运行在 CMD 脚本期间修改主机文件的脚本。如果通过Dockerfile中的 RUN bash ./modifyHostsFile.sh 运行它,它将被添加到该容器中,但随后Docker将继续进行Dockerfile中的下一步并创建一个新的容器(它为Dockerfile中的每个步骤创建一个新的中间容器),并且您对 / etc / hosts 所做的更改将被覆盖。


You have to run the script that modifies your hosts file during your CMD script. If you run it via RUN 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.