Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve docker host names (/etc/hosts) in containers

Tags:

docker

how is it possible to resolve names defined in Docker host's /etc/hosts in containers? Containers running in my Docker host can resolve public names (e.g. www.ibm.com) so Docker dns is working fine. I would like to resolve names from Docker hosts's (e.g. 127.17.0.1 smtp) from containers.

My final goal is to connect to services running in Docker host (e.g. smtp server) from containers. I know I can use the Docker Host IP (127.17.0.1) from containers, but I thought that Docker would have used the Docker host /etc/hosts to build containers's resolve files as well.

I am even quite sure I have seen this working a while ago... but I could be wrong.

Any thoughts?

Giovanni

like image 205
gxvigo Avatar asked Mar 28 '17 10:03

gxvigo


People also ask

How do I edit a ETC host in a container?

Generally speaking, /etc/hosts file can not be modified before running the docker container. However, current docker has an option “–add-host” which adds host-entries onto /etc/hosts when the container is run.

How do I assign a hostname to a docker container?

Basic idea is to use docker inspect to obtain the pid of the container, then enter the uts namespace of the container via nsenter . Running hostname inside that namespace will change the hostname for the docker instance that shares that namespace. Save this answer.

What is the host name of a docker container?

In the same way, a container's hostname defaults to be the container's ID in Docker. You can override the hostname using --hostname . When connecting to an existing network using docker network connect , you can use the --alias flag to specify an additional network alias for the container on that network.

Does docker use host etc hosts?

Docker maps the host's /etc/hosts into the container at startup. Hence you can add the static mapping in your host's /etc/hosts, you can add some lines to /etc/hosts from command line for docker run with --add-host="..." , or you can derive a new image with an ENTRYPOINT , that changes the file.


1 Answers

Check out the --add-host flag for the docker command: https://docs.docker.com/engine/reference/run/#managing-etchosts

$ docker run --add-host="smtp:127.17.0.1" container command

In Docker, /etc/hosts cannot be overwritten or modified at runtime (security feature). You need to use Docker's API, in this case --add-host to modify the file.

For docker-compose, use the extra_hosts option.

For the whole "connect to services running in host" problem, see the discussion in this GitHub issue: https://github.com/docker/docker/issues/1143.

The common approach for this problem is to use --add-host with Docker's gateway address for the host, e.g. --add-host="dockerhost:172.17.42.1". Check the issue above for some scripts that find the correct IP and start your containers.

like image 131
jdno Avatar answered Nov 15 '22 08:11

jdno