Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker RUN append to /etc/hosts in Dockerfile not working

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 ...?

like image 251
Rob McFeely Avatar asked Dec 08 '14 11:12

Rob McFeely


3 Answers

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
like image 114
kev Avatar answered Nov 10 '22 03:11

kev


If you use docker-compose, use extra_hosts:

extra_hosts:
  - "somehost:162.242.195.82"
  - "otherhost:50.31.209.229"
like image 31
andi Avatar answered Nov 10 '22 02:11

andi


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.

like image 1
kralos Avatar answered Nov 10 '22 01:11

kralos