Adding entries to Pod /etc/hosts with HostAliases

    Modification not using HostAliases is not suggested because the file is managed by the kubelet and can be overwritten on during Pod creation/restart.

    Start an Nginx Pod which is assigned a Pod IP:

    1. pod/nginx created

    Examine a Pod IP:

    1. kubectl get pods --output=wide
    1. NAME READY STATUS RESTARTS AGE IP NODE
    2. nginx 1/1 Running 0 13s 10.200.0.4 worker0

    The hosts file content would look like this:

    1. # Kubernetes-managed hosts file.
    2. 127.0.0.1 localhost
    3. ::1 localhost ip6-localhost ip6-loopback
    4. fe00::0 ip6-localnet
    5. fe00::0 ip6-mcastprefix
    6. fe00::1 ip6-allnodes
    7. 10.200.0.4 nginx

    In addition to the default boilerplate, you can add additional entries to the hosts file. For example: to resolve foo.local, to 127.0.0.1 and foo.remote, bar.remote to 10.1.2.3, you can configure HostAliases for a Pod under .spec.hostAliases:

    service/networking/hostaliases-pod.yaml

    1. apiVersion: v1
    2. kind: Pod
    3. metadata:
    4. name: hostaliases-pod
    5. spec:
    6. restartPolicy: Never
    7. hostAliases:
    8. - ip: "127.0.0.1"
    9. hostnames:
    10. - "foo.local"
    11. - "bar.local"
    12. - "foo.remote"
    13. - "bar.remote"
    14. containers:
    15. - name: cat-hosts
    16. image: busybox:1.28
    17. command:
    18. - cat
    19. args:
    20. - "/etc/hosts"

    You can start a Pod with that configuration by running:

    1. kubectl apply -f https://k8s.io/examples/service/networking/hostaliases-pod.yaml

    Examine a Pod’s details to see its IPv4 address and its status:

    1. kubectl get pod --output=wide
    1. NAME READY STATUS RESTARTS AGE IP NODE
    2. hostaliases-pod 0/1 Completed 0 6s 10.200.0.5 worker0

      with the additional entries specified at the bottom.

      The kubelet manages the file for each container of the Pod to prevent the container runtime from modifying the file after the containers have already been started. Historically, Kubernetes always used Docker Engine as its container runtime, and Docker Engine would then modify the /etc/hosts file after each container had started.

      Current Kubernetes can use a variety of container runtimes; even so, the kubelet manages the hosts file within each container so that the outcome is as intended regardless of which container runtime you use.

      Caution:

      If you make manual changes to the hosts file, those changes are lost when the container exits.