Search code examples
kuberneteskubernetes-statefulset

How to set the Pod DNS in Kubernetes


I wanted to know if there is any way that I can set a DNS for the Pod in the StatefulSet, so I can call them directly.

I have read the Kubernetes documentation, but I haven't seen anything useful.


Solution

  • You can directly hit the POD if using the statefulset with headless service

    So if you have three replicas running web-0, web-1, web-2 you can use curl

    web-0.<service-name>.<namespace-name>.svc.cluster.local
    

    POD name

    <pod-name>.<service-name>.<namespace-name>.svc.cluster.local
    

    But the important part is your service should be headless

    Example

    apiVersion: v1
    kind: Service
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      ports:
      - port: 80
        name: web
      clusterIP: None
      selector:
        app: nginx
    ---
    apiVersion: apps/v1
    kind: StatefulSet
    metadata:
      name: web
    spec:
      selector:
        matchLabels:
          app: nginx
      serviceName: "nginx"
      replicas: 3 
      minReadySeconds: 10 
      template:
        metadata:
          labels:
            app: nginx 
        spec:
          terminationGracePeriodSeconds: 10
          containers:
          - name: nginx
            image: registry.k8s.io/nginx
            ports:
            - containerPort: 80
              name: web
    

    Official doc ref : https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#stable-network-id