2 min read | by Jordi Prats
The /etc/hosts file is a Kubernetes-managed file so we cannot add entries freely to it. If we want to add entries to it we will have to use the hostAliases field in the Pod's spec.
$ kubectl exec -it demo-pod -- 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.103.198.74 demo-pod
Adding entries on the pod's /etc/hosts comes really handy when we want to override some domains just for the given pod. To do so we just need to include the entry on the Pod's spec.
The /etc/hosts format is the following:
IP_address canonical_hostname [aliases...]
The hostAliases format allows us to define as many aliases as we want using the hostnames array:
apiVersion: v1
kind: Pod
metadata:
name: demo-pod
spec:
containers:
- command:
- sh
- /code/apply.sh
image: alpine
name: demo
hostAliases:
- hostnames:
- example.pet2cattle.com
ip: 1.2.3.4
Checking on the running pod we will see how it generates the following /etc/hosts file:
$ kubectl exec -it demo-pod -- 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.103.198.74 demo-pod
# Entries added by HostAliases.
1.2.3.4 example.pet2cattle.com
For more details you can check the kubernetes documenentation about hostAliases
Posted on 11/05/2021