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

Anto picture Anto · Feb 4, 2015 · Viewed 7k times · Source

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 ?

Answer

Jens Piegsa picture Jens Piegsa · Feb 4, 2015

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.