【问题标题】:How to edit /etc/hosts file in running docker container如何在运行的 docker 容器中编辑 /etc/hosts 文件
【发布时间】:2016-10-18 01:17:53
【问题描述】:

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

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

【问题讨论】:

  • 将此更改放在 Dockerfile 中会修改映像,而不是正在运行的容器。您是否尝试通过在容器内或主机系统上运行的命令来修改 /etc/host?
  • 是的,如果可能的话。我也尝试过使用升级版的 docker,其中有 CreateContainerCmd 类,该类包含一个名为 withExtraHosts(String ...hosts) 的函数,但这也没有用。

标签: docker centos7


【解决方案1】:

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

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

此链接也可能有用:- https://github.com/docker/docker/issues/10324

【讨论】:

    【解决方案2】:

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

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

    作品

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

    # modify the hosts file
    bash ./modifyHostsFile.sh
    

    不工作

    在 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 的更改将被覆盖。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-04
        • 1970-01-01
        • 2015-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多