Is it possible to have under Kubernetes the Pod hostname be the hosting Node hostname?

3/18/2019

Moving from Docker to K8s, today we run some containers with: docker run --hostname %H ... that causes the container to get the Host machine hostname as its own, can I have similar behavior running under K8s? (having the pod hostname as the Node hostname)

From what I have seen so far:

  1. spec.hostname seems not to support values from env vars.

  2. Using hostAliases seems to put a hardcoded name...

BTW, the pods are deployed as a DeamonSet

-- Doron Levi
docker
kubernetes

1 Answer

5/15/2019

If you use hostNetwork: true for pod's spec, it will share the network with the node. Here is a simple test:

apiVersion: v1
kind: Pod
metadata:
  name: test-pod
spec:
  hostNetwork: true
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "sh", "-c"]
      args:
      - while true; do
          echo -en '\n';
          printenv HOSTNAME
          sleep 10;
        done;
  restartPolicy: Never

That shows that the pod's host name is the same as its node.

Note though that this setup is general not recommended:

Avoid using hostNetwork, for the same reasons as hostPort

However, maybe in your case that's not an issue.

-- BartoszKP
Source: StackOverflow