如何在正在运行的Docker容器中编辑/ etc / hosts文件 [英] How to edit /etc/hosts file in running docker container

查看:759
本文介绍了如何在正在运行的Docker容器中编辑/ etc / hosts文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

推荐答案

推荐的解决方案是将-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



< h2>不起作用在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.

这篇关于如何在正在运行的Docker容器中编辑/ etc / hosts文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆