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

后端 未结 3 2118
青春惊慌失措
青春惊慌失措 2020-12-29 14:39

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 a

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 15:17

    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.

    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

    Works

    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"]
    

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

    # modify the hosts file
    bash ./modifyHostsFile.sh
    

    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"]
    

    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.

提交回复
热议问题