Help Center/Cloud Container Engine/Best Practices/Container/Configuring the /etc/hosts File of a Pod Using hostAliases
Updated on 2026-03-23 GMT+08:00

Configuring the /etc/hosts File of a Pod Using hostAliases

Application Scenarios

If DNS or other related settings are inappropriate, you can use hostAliases to overwrite the resolution of the hostname at the pod level when adding entries to the /etc/hosts file of a pod.

Procedure

  1. Use kubectl to access the cluster.
  2. Create a hostaliases-pod.yaml file.

    vi hostaliases-pod.yaml

    The field in bold in the YAML file indicates the image name and tag. You can replace the example value as required.

    apiVersion: v1
    kind: Pod
    metadata:
      name: hostaliases-pod
    spec:
      hostAliases:
      - ip: 127.0.0.1
        hostnames:
        - foo.local
        - bar.local
      - ip: 10.1.2.3
        hostnames:
        - foo.remote
        - bar.remote
      containers:
        - name: cat-hosts
          image: tomcat:9-jre11-slim
          lifecycle:
            postStart:
              exec:
                command:
                  - cat
                  - /etc/hosts
      imagePullSecrets:
        - name: default-secret
    Table 1 pod field description

    Parameter

    Mandatory

    Description

    apiVersion

    Yes

    API version

    kind

    Yes

    Type of an object to be created

    metadata

    Yes

    Metadata definition of a resource object

    name

    Yes

    Name of a pod

    spec

    Yes

    Detailed description of a pod. For details, see Table 2.

    Table 2 spec field description

    Parameter

    Mandatory

    Description

    hostAliases

    Yes

    Host alias

    containers

    Yes

    For details, see Table 3.

    Table 3 containers field description

    Parameter

    Mandatory

    Description

    name

    Yes

    Container name

    image

    Yes

    Container image name

    lifecycle

    No

    Lifecycle

  3. Create the pod.

    kubectl create -f hostaliases-pod.yaml

    If information similar to the following is displayed, the pod has been created:

    pod/hostaliases-pod created

  4. Query the pod status.

    kubectl get pod hostaliases-pod

    If the pod is in the Running state, the pod has been created:

    NAME                  READY          STATUS       RESTARTS      AGE
    hostaliases-pod       1/1            Running      0             16m

  5. Check whether hostAliases functions properly.

    docker ps |grep hostaliases-pod

    docker exec -ti Container ID /bin/sh