Home > OS >  Modify /etc/hosts in Docker build
Modify /etc/hosts in Docker build

Time:10-16

I know Docker doesn't want us editing the /etc/hosts file

However I still really want to. Or something very close to it anyway. I have an nginx reverse proxy running as a Docker container. As part of that build process, I want to run nginx -t to test the validity of the nginx.conf file. Unfortunately, the conf file refers to hosts (e.g. rest-service) that will only exist at run time (as part of a Docker Swarm or Kubernetes DNS resolution).

So I figured I could do something like:

RUN cp -f /etc/hosts /etc/hosts.bak && \
    echo "127.0.0.1 rest-service" >> /etc/hosts && \
    nginx -t && \
    cp -f /etc/hosts.bak /etc/hosts

Basically backup the nginx.conf file, create a temporary one that will just resolve to localhost, run the nginx test, and then copy the real one back in place. Unfortunately, that gives the somewhat predictable error:

/bin/sh: 1: cannot create /etc/hosts: Read-only file system

Any clever ideas on how to validate the nginx.conf file during the build process?

CodePudding user response:

Never mind... I didn't think the --add-host parameter would work for the build command, or if it did that the host modification would bake into the image. Turns out it works fine for my purpose:

docker build -t ... --add-host rest-service:127.0.0.1 ...

And on an instantiated container, no trace of the addition.

  • Related