Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the hostname for a container running in Kubernetes

I want to set the hostname in a container running inside Kubernetes, but Kubernetes appears to be overriding whatever I set at runtime.

I've tried both setting /etc/hostname in the docker image I'm having Kubernetes use, and including echo "host.example.com > /etc/hostname" in the CMD in the Dockerfile.

There appears to be a docker flag -h to set the hostname. Is there a way for me to specify in my replication controller that it should start the container with a special flag?

The container's Debian, if it helps.

like image 632
Derek Gonyeo Avatar asked Jul 22 '15 01:07

Derek Gonyeo


People also ask

What is the hostname of a container?

In the same way, a container's hostname defaults to be the container's ID in Docker. You can override the hostname using --hostname . When connecting to an existing network using docker network connect , you can use the --alias flag to specify an additional network alias for the container on that network.

What is a Kubernetes hostname?

The hostname of a Container is the name of the Pod in which the Container is running. It is available through the hostname command or the gethostname function call in libc. The Pod name and namespace are available as environment variables through the downward API.


2 Answers

My previous answer was incorrect, edited with correct info

The -h flag for docker run will set the hostname of the container when you create it.

Test it out: docker run -h test.example.com -it ubuntu /bin/bash

The docker start command does not have the same -h or --hostname argument though. It doesn't seem possible to change the hostname of an existing container, just a new one from an image.

However w/r/t Kubernetes: There is an open issue on Github regarding how Kubernetes handles hostnames. It does not seem like Kubernetes exposes docker's hostname setting directly, but you might be able to influence it via your pod name

like image 129
edhurtig Avatar answered Oct 12 '22 17:10

edhurtig


I found the answer for changing the docker hostname after the container has been running or I can say to the existing container here are some steps

  1. Run

    docker inspect -f '{{ .State.Pid }}' <existing_docker_hostname> 

    Output will be a number <15580>

  2. Run this command to login to the container

    nsenter --target 15580 --uts 
  3. Run this command to change the hostname

    hostname "node_js" 

now exit the container and login again you will see the hostname has been changed.

like image 21
user9395071 Avatar answered Oct 12 '22 16:10

user9395071