CodeBlanks Logo Icon CodeBlanks

StatefulSet YAML

Learn the StatefulSet YAML structure.

StatefulSet YAML

The StatefulSet YAML is similar to a Deployment's; additionally, serviceName is required. It's the name of the headless service that gives the pods DNS records:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db
  replicas: 3
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: postgres
          image: postgres:16
          ports:
            - containerPort: 5432

The headless service

A service with clusterIP: None gets no virtual IP; a DNS query returns the pod IPs directly and each StatefulSet pod gets its own record in the form pod-name.service-name. That way clients can connect to a specific replica (e.g. the primary):

apiVersion: v1
kind: Service
metadata:
  name: db
spec:
  clusterIP: None
  selector:
    app: db
  ports:
    - port: 5432

# db-0.db.default.svc.cluster.local -> 10.244.1.12
# db-1.db.default.svc.cluster.local -> 10.244.2.15

Practice StatefulSet and headless service

Write a StatefulSet YAML: name db, serviceName: db, replicas: 3; selector and template label app: db; container named postgres, image postgres:16.

Starter code

terminal
# buraya yaz

Sample solution

terminal
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db
  replicas: 3
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: postgres
          image: postgres:16
          ports:
            - containerPort: 5432

Expected output

statefulset.apps/db created

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is serviceName required in a StatefulSet?

  • It determines the labels
  • It names the headless service that gives each pod a stable DNS name like db-0.db Correct answer
  • It creates a load balancer
  • It gives an external IP

Explanation: The service must be created separately; the StatefulSet doesn't create it itself.

2 Make the service headless.

Question
spec:
  clusterIP: ____
Answer
spec:
  clusterIP: None

Explanation: clusterIP: None allocates no virtual IP.

3 Match.

Term Meaning
serviceName Headless service name
clusterIP: None No virtual IP
db-0.db Pod DNS name
kind: StatefulSet apps/v1

All lessons in Advanced