How to get "add-hosts" property of Docker Compose in Kubernetes

Ajeet Singh Raina - Jan 23 '23 - - Dev Community

In Kubernetes, you can use a Pod or Deployment with a hostAliases field to achieve similar functionality to the add-hosts property in a docker-compose file. The hostAliases field allows you to specify a hostname and its corresponding IP address, which will be added to the /etc/hosts file on the container.

Here is an example of a Pod definition with hostAliases:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  hostAliases:
  - ip: "10.0.0.1"
    hostnames:
    - "example.com"
    - "my-alias"
  containers:
  - name: my-container
    image: my-image
Enter fullscreen mode Exit fullscreen mode

This will add the following entries to the /etc/hosts file inside the container:

10.0.0.1 example.com
10.0.0.1 my-alias
Enter fullscreen mode Exit fullscreen mode

You can also use hostAliases in Deployment yaml file as well.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  template:
    spec:
      hostAliases:
      - ip: "10.0.0.1"
        hostnames:
        - "example.com"
        - "my-alias"
      containers:
      - name: my-container
        image: my-image
Enter fullscreen mode Exit fullscreen mode

This will add the same entries inside all the pod's which are created under this Deployment.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .