83

I'm having trouble setting the hostname on a running docker container. I'm also having trouble understanding how to specify hostname after the image is started.

I started a container from an image I downloaded:

sudo docker run -p 8080:80 -p 2222:22 oskarhane/docker-wordpress-nginx-ss

But I forgot to specify hostname through -h; how can I specify the hostname now that the container is running?

kenorb
  • 7,125

7 Answers7

76

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
Lætitia
  • 2,115
amitmula
  • 900
11

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
Tomot
  • 449
8

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

chicks
  • 3,915
  • 10
  • 29
  • 37
5

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

James V
  • 67
1

https://evolvingweb.ca/blog/changing-docker-hostnames-namespaces describes a way to do this. 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.

0

As a few others have pointed out, this can be changed for containers by modifying the config.v2.json file.

Just be sure the Docker service is stopped before the file is edited, else it will be OVERWRITTEN. The steps MUST be done in this order

  • Stop the Container
  • Stop the Docker service
  • Modify the - /var/lib/docker/containers/CONTAINER_ID/config.v2.json - file

  • Start up the Docker service

  • Start the container

This has been confirmed working for me on Docker v17.05.0-ce, on a container using --net=host. Modifying the /etc/hostname file does not work and the file is just overwritten.

-3

In

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

find and set

"Config":{"Hostname":"utils","Domainname":"mysite.com", ...}