如何在 运行 docker 容器中编辑 /etc/hosts 文件

How to edit /etc/hosts file in running docker container

我正在开发一个需要将一些配置存储在 docker 容器的 /etc/hosts 文件中的应用程序。 我尝试了很多选项,但没有找到在 运行 时间修改 /etc/hosts 文件的任何正确方法。

我想通过 Dockerfile 或 java 代码来完成。 我能够构建 docker 图像并手动修改 /etc/hosts 文件,但不幸的是,这不是我们的项目要求。

取决于你想做什么样的修改。如果您只需要添加更多主机,您可以在 docker 运行 命令中完成,例如 -

docker run --add-host="localA:127.0.0.1" --add-host="localB:172.0.0.1" ....

这个 link 也可能有用:- https://github.com/docker/docker/issues/10324

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

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

有效

在Docker文件中

# 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 脚本中我执行该脚本来修改主机文件

# modify the hosts file
bash ./modifyHostsFile.sh

不起作用

在Docker文件中

# 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 脚本期间修改您的主机文件的脚本。如果您 运行 通过 Docker 文件中的 RUN bash ./modifyHostsFile.sh 将其添加到该容器中,但随后 Docker 将继续 Docker 中的下一步文件并创建一个新容器(它为 Docker 文件中的每个步骤创建一个新的中间容器)并且您对 /etc/hosts 的更改将被覆盖。

我遇到了同样的问题,并在 ex 模式下使用 vi 解决了它。

ex -sc '%s/foo/bar/g|x' /etc/hosts