In a project recently I had a need to add an entry to /etc/hosts and being new to Docker I was surprised to find that hosts is read only. Turns out this is a known issue, but I was able to find a work around. Essentially creating a copy of the library that handles hostname resolution and editing it to replace /etc/hosts with the path of a writable hosts file. Sounds daunting but it isn't all that scary, here's the step by step:

  1. Create a writable copy of /etc/hosts somewhere where the path will be the same length. I used /tmp/hosts:

    RUN cp /etc/hosts /tmp/hosts
  2. Then you need to make a copy of that you can edit:

    RUN mkdir -p -- /lib-override && cp /lib/x86_64-linux-gnu/ /lib-override
  3. Now edit the binary to replace /etc/hosts with the path to the writable hosts file (ex. /tmp/hosts):

    RUN perl -pi -e 's:/etc/hosts:/tmp/hosts:g' /lib-override/
  4. Finish up by letting the system know where to find the edited binary:

    ENV LD_LIBRARY_PATH /lib-override