I have a simple Dockerfile but the first RUN command (to append a host IP address to /etc/hosts) has no effect
FROM dockerfile/java
RUN sudo echo "XX.XX.XXX.XXX some.box.com MyFriendlyBoxName" >> /etc/hosts
ADD ./somejavaapp.jar /tmp/
#CMD java -jar /tmp/somejavaapp.jar
EXPOSE 8280
I build using
docker build .
and then test the RUN echo line has worked using
sudo docker run -t -i <built image ID> /bin/bash
I am then into the container but the /etc/hosts file has not been appended. Running the same echo .... line while now in the container has the desired effect
Can anyone tell me what is wrong with my dockerfile RUN ...?
Docker will generate /etc/hosts
dynamically every time you create a new container. So that it can link others. You can use --add-host
option:
docker run --add-host www.domain.com:8.8.8.8 ubuntu ping www.domain.com
If you use docker-compose, use extra_hosts:
extra_hosts:
- "somehost:162.242.195.82"
- "otherhost:50.31.209.229"
If you are trying to maintain the hosts file entries between host machine and container another way would be to wrap your command with a shell script that maps your hosts' /etc/hosts
into --add-host
params:
~/bin/java
:
#!/bin/sh
ADD_HOSTS=$(tail -n +10 /etc/hosts | egrep -v '(^#|^$)' | sed -r 's/^([a-z0-9\.\:]+)\s+(.+)$/--add-host="\2:\1"/g')
eval docker run \
-it \
--rm \
$ADD_HOSTS \
<image> \
java $*
return $?
Obviously replace java with whatever you are trying to do...
Explanation; ADD_HOSTS
will take everything after the first 10 lines in your hosts' /etc/hosts
file |
remove comments and blank lines |
re-order the entries into --add-host
params.
The reason for taking everything after the first 10 lines is to exclude the localhost and ipv6 entries for your host machine. You may need to adjust this to suit your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With