Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add my container's hostname to /etc/hosts?

Tags:

docker

hosts

In order to support some old software solutions, I need to bind my container's hostname to 127.0.0.1, leaving me with something like this:

$ hostname
4e84a7ae5f92
$ cat /etc/hosts | grep 127.0.0.1
127.0.0.1       localhost 4e84a7ae5f92

Best case scenario would be to do in the Dockerfile, but since docker build builds an image (and not a container), it doesn't seem realistic.
Also if I try to do it with sed in the running container, I end up with an error:

$ sed -i '/^127\.0\.0\.1.*/ s/$/ '$(hostname)'/' /etc/hosts
sed: cannot rename /etc/sedC5PkA2: Device or resource busy

What can I do ?

like image 257
Anto Avatar asked Feb 04 '15 17:02

Anto


2 Answers

The docker run command has an option named --hostname="" which takes care of your /etc/hostname file.

The host-to-ip mapping in the /etc/hosts file can be managed with the option --add-host=[] then.

like image 154
Jens Piegsa Avatar answered Nov 18 '22 04:11

Jens Piegsa


The correct way to add the container name to /etc/hosts is using the flag --add-host. In your case, suppose that you want to create and start a new container named <container-name> using the image <image-name> in detached mode:

docker run --name <container-name> --add-host <container-name>:127.0.0.1 -d <image-name>`

This will create the following /etc/hosts (please note the last line):

127.0.0.1       localhost
127.0.0.1       4e84a7ae5f92

It has been tested using Docker 1.12.0-rc2.

like image 28
Alexandre V. Avatar answered Nov 18 '22 02:11

Alexandre V.