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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With