Is it possible to set hostname to Pod when using hostNetwork in kubernetes?

4/16/2018

I'm new to Kubernetes and recently I am using it to deploy hadoop. I want to do a thing that set a specific hostname to pod which is created using statefulSets with hostNetwork = true.

Here is my yaml config file.

apiVersion: v1
kind: Service
metadata:
  name: test-bbox
  labels:
    app: test-bbox
spec:
  clusterIP: None
  selector:
    app: test-bbox
  ports:
  - name: foo
    port: 1234
    targetPort: 1234
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: test-bbox
spec:
  serviceName: "test-bbox"
  replicas: 1
  selector:
    matchLabels:
      app: test-bbox
  template:
    metadata:
      labels:
        app: test-bbox
    spec:
      hostNetwork: true
      hostname: test-hostname
      containers:
        - image: busybox
          name: busybox
          env:
          - name: MY_POD_NAME
            valueFrom:
              fieldRef:
                fieldPath: metadata.name
          command:
            - sleep
            - "7200"

As the yaml says, the attribute hostnetwork is set to true. Then the pod test-bbox-0's hostname is the hostname of the Node where it is created.

If I set hostnetwork to false, the hostname is auto-generated by statefulSets as a format such as test-bbox-0.test-bbox.default.svc.cluster.local, which is just I need.

But in my case I need to set hostnetwork to true and at the same time to customize the hostname to the format mentioned above rather than the Node's hostname.

So the question is, is there any way to customize hostname for Pod ?

Kubernetes version used : 1.9

-- Jerry Zhang
kubernetes

1 Answer

4/16/2018

It is not possible to set the hostname for a Pod that is using hostNetwork. If you try to change the hostname in such a Pod you'll see that you are changing the hostname of the node too; this is because they are sharing the UTS namespace, not only the networking one.

Pods managed by a StatefulSet are a special case and their hostname is set my StatefulSet and it can't be configured directly. The hostname can be influenced by the name of StatefulSet itself while domainname by naming the Service appropriately:

Each Pod in a StatefulSet derives its hostname from the name of the StatefulSet and the ordinal of the Pod. The pattern for the constructed hostname is $(statefulset name)-$(ordinal). [...] A StatefulSet can use a Headless Service to control the domain of its Pods. The domain managed by this Service takes the form: $(service name).$(namespace).svc.cluster.local, where cluster.local is the cluster domain. As each Pod is created, it gets a matching DNS subdomain, taking the form: $(podname).$(governing service domain), where the governing service is defined by the serviceName field on the StatefulSet.

-- Janos Lenart
Source: StackOverflow