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

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.


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