13

I'm new to Docker and trying to understand what is the best way to insert docker parent host ip into container hosts file.

I'm using the following command in my Dockerfile

RUN /sbin/ip route|awk '/default/ { print $3,"\tdockerhost" }' >> /etc/hosts

but sometimes hosts ip get change so its non relevant anymore...

The reason to do that, if you ask yourself, is that i need to access another 2 dockers containers (and link not offer this feature).

Thanks,

Idan Gozlan
  • 3,173
  • 3
  • 30
  • 47
  • I need docker host's ip to be in /etc/hosts file. – Idan Gozlan Nov 11 '14 at 12:19
  • 2
    The problem is not with awk, it is with running the command at the wrong time. Kind of like compile-time vs run-time. – Bryan Nov 11 '14 at 12:23
  • Linking is the way to achieve it, it is meant to give access to other docker containers. Explain your use case better and how linking does not work for you. – Motin Mar 19 '15 at 10:10

2 Answers2

13

The --add-host option is made for this. So, in your docker run command, do something like:

docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print  $3}'` [my container]
FabianCook
  • 20,269
  • 16
  • 67
  • 115
Bryan
  • 11,398
  • 3
  • 53
  • 78
  • 1
    Are you sure that arg will be valid also after reboot when host ip getting change? it looks like it valid only for creation... – Idan Gozlan Nov 11 '14 at 12:27
  • Ah, you mean if you let Docker restart your containers on reboot? Yes, that would be a problem. You can restart things differently - see https://docs.docker.com/articles/host_integration/. If you want a dynamic scheme to resolve an address, maybe use DNS? – Bryan Nov 11 '14 at 12:40
  • 1
    The command `/sbin/ip route|awk '/default/ { print $3}'` runs in docker host, instead of in docker container, which produces the wrong ip result. – Sergio Santiago Dec 31 '15 at 17:26
  • @santiago this is what the OP asked for. – Bryan Jan 07 '16 at 10:38
  • 3
    Does anyone know if it's possible to use this with Docker compose's [`extra_hosts:`](https://docs.docker.com/compose/compose-file/#/extra-hosts) configuration? – davetapley Aug 02 '16 at 22:29
5

--add-host option can be used when you create/run your container but since /sbin/ip command isn't available in operating systems like OSX, we can use a more generic solution:
docker run --add-host=dockerhost:`docker network inspect \ --format='{{range .IPAM.Config}}{{.Gateway}}{{end}}' bridge` [IMAGE]

Gongora
  • 595
  • 6
  • 10