Dockerfile HOSTNAME Instruction for docker build like docker run -h

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.


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.