Assigning containers host name to 127.0.0.1 in hosts file - kubernetes container

4/10/2020

I would like to add en entry in the etc/hosts inside the container as following

127.0.0.1 hostname-of-pod

and i got this link which explains how to add an host entry, however i would like to know what we need to add to get that hostname-of-pod

-- doc_noob
kubernetes

3 Answers

4/10/2020

You can inject the node name or host IP into environment variables in a pod using the downward API

see https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/#use-pod-fields-as-values-for-environment-variables for more info

I believe that the part you were looking for is this:

        - name: MY_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name

Source: https://github.com/kubernetes/client-go/issues/565

-- omricoco
Source: StackOverflow

4/10/2020

You can simply append 127.0.0.1 hostname-of-pod by:

Command 1: kubectl exec -n namespace -it pod_name sh
Command 2: echo "127.0.0.1    $HOSTNAME" >> /etc/hosts 

Note Command 2 needs to execute inside pod after command 1 succeed.

-- Dinesh Katwal
Source: StackOverflow

4/10/2020

however i would like to know what we need to add to get that hostname-of-pod

It should already be in /etc/hosts for Pod. K8s handles it for users.

$ kubectl get pods
NAME                       READY   STATUS    RESTARTS   AGE
busybox-68dc67fcc5-gwd95   1/1     Running   6          6h52m

$ kubectl exec -it busybox-68dc67fcc5-gwd95 -- sh

# cat /etc/hosts
# Kubernetes-managed hosts file.
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
10.60.0.17  busybox-68dc67fcc5-gwd95

Hope that helps!

-- Nick
Source: StackOverflow