Dockerfile HOSTNAME Instruction for docker build like docker run -h

后端 未结 3 2040
故里飘歌
故里飘歌 2021-01-02 16:39

I am attempting to set the hostname inside a docker container during the build since certain software installs use the discovered randomly generated hostname and permanently

相关标签:
3条回答
  • 2021-01-02 17:13

    I have recently had a similar issue.

    The solution that worked for me was to set the hostname in the container namespace. To do that automatically I have put together the following docker build script:

    docker build . | tee >((grep --line-buffered -Po '(?<=^change-hostname ).*' || true) | while IFS= read -r id; do nsenter --target "$(docker inspect -f '{{ .State.Pid }}' "$id")" --uts hostname 'new-hostname'; done)
    

    Right at the end new-hostname can be replaced with the desired hostname.

    My Dockerfile looks like this:

    RUN echo "change-hostname $(hostname)"; \
        sleep 1; \
        printf '%s\n' "$(hostname)" > /etc/hostname; \
        printf '%s\t%s\t%s\n' "$(perl -C -0pe 's/([\s\S]*)\t.*$/$1/m' /etc/hosts)" "$(hostname)" > /etc/hosts; \
        echo 'Installing more stuff...'
    

    The first line that prints out change-hostname $(hostname) (where hostname should print out the current container id) signals the buildscript to change the hostname for that container. The build script then queries the pid for the container and executes hostname 'new-hostname' in its uts namespace. The sleep 1 just gives the build script some time to adjust the hostname properly. Then I modify /etc/hostname and /etc/hosts to include the newly set hostname.

    This even changes the output of uname -n so I am pretty sure it would work as a solution for the original question.

    0 讨论(0)
  • 2021-01-02 17:20

    Let me see if I understand your question, you would like to build an image that when run as a container has the runtime hostname even if the hostname used for building is not the same. Correct? If so, my question to you is the following, are you able to reconfigure the software to have a new hostname after it is installed?

    If this is possible, I would recommend writing a script that is able to modify the hostname and use this script as an ENTRYPOINT. This way you can guarantee that you have corrected the hostname anytime your container is run (with any command) and you don't spend time trying to force support for a particular hostname through at build time, which, by your own admission, is difficult to do.

    0 讨论(0)
  • 2021-01-02 17:28

    You can use docker-compose to build your image and assign the hostname, e.g.

    version: '3'
    services:
      all:
        image: testimage
        container_name: myname
        hostname: myhost
        build:
          context: .
    

    The run as: docker-compose --build up.

    0 讨论(0)
提交回复
热议问题