July 16, 2014
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:
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
Then you need to make a copy of libnss_files.so
that you can edit:
RUN mkdir -p -- /lib-override && cp /lib/x86_64-linux-gnu/libnss_files.so.2 /lib-override
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/libnss_files.so.2
Finish up by letting the system know where to find the edited binary:
ENV LD_LIBRARY_PATH /lib-override
Written by Jason Worley who lives and works in Indianapolis building useful things.