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:
pod/nginx created
Examine a Pod IP:
kubectl get pods --output=wide
NAME READY STATUS RESTARTS AGE IP NODE
nginx 1/1 Running 0 13s 10.200.0.4 worker0
The hosts file content would look like this:
# 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
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
apiVersion: v1
kind: Pod
metadata:
name: hostaliases-pod
spec:
restartPolicy: Never
hostAliases:
- ip: "127.0.0.1"
hostnames:
- "foo.local"
- "bar.local"
- "foo.remote"
- "bar.remote"
containers:
- name: cat-hosts
image: busybox
command:
- cat
args:
- "/etc/hosts"
You can start a Pod with that configuration by running:
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:
kubectl get pod --output=wide
NAME READY STATUS RESTARTS AGE IP NODE
hostaliases-pod 0/1 Completed 0 6s 10.200.0.5 worker0
with the additional entries specified at the bottom.
The kubelet the file for each container of the Pod to prevent Docker from modifying the file after the containers have already been started.
Caution:
Avoid making manual changes to the hosts file inside a container.