How to specify hostname for the running container?

Solution 1:

Edit /etc/hostname is one thing for which you need ssh access inside the container. Otherwise, you can spin up the container with -h option.

To set the host and domain names:

$ docker run -h foo.bar.baz -i -t ubuntu bash
root@foo:/# hostname
foo
root@foo:/# hostname -d
bar.baz
root@foo:/# hostname -f
foo.bar.baz

Solution 2:

Stop container and service

sudo docker stop CONTAINER_NAME
sudo service docker stop

Edit config file (JSON) [You should make backup first]

/var/lib/docker/containers/CONTAINER_ID/config.json

Replace

"Hostname":"WHATEVER"

with

"Hostname":"NEW_HOSTNAME"

Start container and service

sudo service docker start
sudo docker start CONTAINER_NAME

(Optionally you can also attach docker)

sudo docker attach CONTAINER_NAME

Details about dockers (i.e. CONTAINER_NAME, CONTAINER_ID) can be obtained by running

sudo docker ps -a

Solution 3:

In case you use --net=host then you can't change the hostname from -h or from inside the docker.

See https://github.com/docker/docker/issues/5708


Solution 4:

Restarting the container would be the easiest option - but you may also edit /etc/hostname and go from there.

Tags:

Linux

Docker

Lxc