Configuring the /etc/hosts File of a Pod Using hostAliases
Applications
In a Kubernetes cluster, pod hostname resolution relies on cluster DNS (such as CoreDNS) by default. However, some pods require localized resolution control for specific domain names without depending on cluster or external DNS. The /etc/hosts file inside a pod is managed by kubelet, and its default content is determined by the cluster network add-on and system configuration. Direct modifications made inside the container are lost after restart or rebuild and cannot be persisted. You can use the hostAliases parameter to add custom resolution entries to the pod's /etc/hosts file.
Procedure
- Use kubectl to access the cluster.
- Create a hostaliases-pod.yaml file.
vi hostaliases-pod.yaml
An example is as follows:
apiVersion: v1 kind: Pod metadata: name: hostaliases-pod spec: hostAliases: # Add the mapping between the custom hostname and IP address. - ip: 127.0.0.1 # Target IP address hostnames: # List of hostnames bound to the IP address - foo.local - bar.local - ip: 10.1.2.3 hostnames: - foo.remote - bar.remote containers: - name: cat-hosts image: tomcat:9-jre11-slim # The image and image tag can be changed based on your requirements. imagePullSecrets: - name: default-secretTable 1 hostAliases parameters Parameter
Type
Description
spec.hostAliases
Object array
List of custom hostname resolution entries, added to the pod's /etc/hosts file without overwriting the default localhost or Kubernetes-related entries. It enables local resolution from hostnames to IP addresses.
spec.hostAliases[].ip
String
Target IP address to be resolved. It must be a valid IP address format.
spec.hostAliases[].hostnames
String array
List of hostnames to be bound to the preceding IP address. Multiple aliases are supported. Each hostname must comply with DNS naming rules.
- Create a pod.
kubectl create -f hostaliases-pod.yaml
If output similar to the following is displayed, the pod has been created:
pod/hostaliases-pod created
- Check the pod status.
kubectl get pod hostaliases-pod
If the pod is in the Running state, it has been created successfully.
NAME READY STATUS RESTARTS AGE hostaliases-pod 1/1 Running 0 16m
- Check whether hostAliases functions properly.
kubectl exec hostaliases-pod -- cat /etc/hosts
You can view the entries added by hostAliases at the end of the file. For example:
# Entries added by HostAliases. 127.0.0.1 foo.local bar.local 10.1.2.3 foo.remote bar.remote
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot