Review the StatefulSet headless Service association

Configure a headless Service for the StatefulSet’s stable network identities.

Description

For stable per-Pod DNS names, create a headless Service with cluster_ip = "None" in the StatefulSet’s namespace. Set spec.service_name to that Service’s name.

Potential impact

An ordinary Service IP or a selector that misses the Pods can prevent peers from finding each other by name during restarts or scaling.

Remediation

Match the Service selector to Pod template labels and check the ports. If the existing Service already has a cluster IP, plan for interruption when replacing it. After the change, test DNS and peer connections for individual Pods.

Examples

Both examples need a Pod template and reference the prometheus Service in monitoring. The ordinary Service needs a port. The headless Service can omit ports when used only to discover Pod addresses.

Before

hcl
resource "kubernetes_service" "example" {
  metadata {
    name      = "prometheus"
    namespace = "monitoring"
  }

  spec {
    selector = {
      app = "prometheus"
    }
  }
}

resource "kubernetes_stateful_set" "example" {
  metadata {
    name      = "prometheus"
    namespace = "monitoring"
  }

  spec {
    service_name = "prometheus"

    selector {
      match_labels = {
        app = "prometheus"
      }
    }
  }
}

After

hcl
resource "kubernetes_service" "example" {
  metadata {
    name      = "prometheus"
    namespace = "monitoring"
  }

  spec {
    cluster_ip = "None"

    selector = {
      app = "prometheus"
    }
  }
}

resource "kubernetes_stateful_set" "example" {
  metadata {
    name      = "prometheus"
    namespace = "monitoring"
  }

  spec {
    service_name = "prometheus"

    selector {
      match_labels = {
        app = "prometheus"
      }
    }
  }
}

Explanation:

  • Before: Omitting cluster_ip gives the Service an ordinary cluster IP.
  • After: cluster_ip = "None" creates a headless Service for the individual Pod addresses. The Pod template needs the label app = "prometheus".

References