Home KubernetesKubernetes StatefulSets: Run Databases That Keep Their Data

Kubernetes StatefulSets: Run Databases That Keep Their Data

by Knowledge Base Linux
Kubernetes StatefulSets giving database pods stable identity and storage

Running a database on Kubernetes feels simple until a pod restarts and its data, its network identity, or its peer address changes without warning. That is exactly the problem kubernetes statefulsets solve. A StatefulSet is a workload controller designed for applications where identity and storage matter, such as databases, message queues, and clustered stateful services. Unlike a stateless web front end, a database pod cannot simply be replaced by any identical copy, because the replacement must find the same data and be reachable at the same address as before.

Kubernetes StatefulSets database pods with stable persistent storage volumes

In this guide you will learn why Deployments are a poor fit for databases, how StatefulSets provide stable pod names, stable network identities, and stable storage, and how to build a practical example with a headless Service and volumeClaimTemplates. You will also learn how ordered scaling and update strategies work, what to back up, and how to fix the most common StatefulSet failures.

Prerequisites

Before you start, you need a working Kubernetes cluster, kubectl configured to reach it, and a StorageClass that can provision volumes dynamically. This kubernetes statefulsets guide assumes you can already create Deployments, Services, and PersistentVolumeClaims, and you know how to check pod status with kubectl get pods and kubectl describe pod. This guide uses PostgreSQL as the example database, but the StatefulSet concepts apply to MySQL, MongoDB, Redis in persistent mode, and many other stateful applications.

Why kubernetes statefulsets Exist: The Database Problem

A Deployment is built for stateless applications. When a Deployment pod dies, Kubernetes creates a replacement with a random name, a new IP address, and no guarantee of keeping the same volume. That behaviour is fine for a web server that reads its configuration at startup and stores nothing locally, but it breaks a database in several ways. First, the new pod may start empty if it does not reattach the old volume. Second, other pods or clients that cached the old pod address will fail to connect. Third, clustered databases often require each member to have a fixed identity so peers can agree on who is the primary and who is a replica.

For a clear comparison of the stateless model, see this explanation of how Kubernetes Deployments and ReplicaSets manage stateless pods. A StatefulSet keeps the opposite contract: each pod gets a stable ordinal index, a stable hostname, and a stable volume that follows that pod across restarts and rescheduling.

Feature Deployment StatefulSet
Pod name Random suffix Stable, with an ordinal such as db-0
Network identity Changes on replacement Stable DNS name per pod
Storage Shared or ephemeral by default One PersistentVolumeClaim per pod
Scaling order Pods created in parallel Created in order, removed in reverse order
Best for Stateless web apps and APIs Databases and clustered stateful apps

How kubernetes statefulsets Keep Identity and Storage

A StatefulSet gives each pod a name made from the StatefulSet name plus an ordinal index starting at zero, for example db-0, db-1, and db-2. The pod keeps that name for its whole lifetime, even if it is deleted and recreated. This stable identity is paired with a headless Service, which is a Service with clusterIP set to None. A headless Service does not assign a single cluster IP or load-balance traffic. Instead, it lets DNS return the individual IP address of each pod, so clients can reach a specific member directly.

With a headless Service named db in the default namespace, the pod db-0 gets a DNS name in the form db-0.db.default.svc.cluster.local. The general pattern is pod-name, then service-name, then namespace, then svc.cluster.local. Database peers use these names to find each other, and an application can connect to a known member instead of guessing which pod is currently running. The StatefulSet field serviceName must match the name of that headless Service, or the stable DNS names will not be created.

Storage works on the same stable principle. A StatefulSet does not use one shared volume for all pods. It uses volumeClaimTemplates, a template that Kubernetes uses to create one PersistentVolumeClaim for each pod. The claim name follows the pattern claim-name, then StatefulSet name, then ordinal, for example data-db-0 for the first pod. When db-0 is deleted and recreated, it reattaches to data-db-0 and sees the same data. When you scale up, new pods get new claims. When you scale down, the old claims are kept by default, which protects your data from accidental loss during a scale-down.

Creating kubernetes statefulsets: A Practical Example

Start with the headless Service. It only needs a selector that matches the StatefulSet pods, a port for the database, and clusterIP set to None. Without the selector match, DNS records will not be created for the pods, and clients will not be able to resolve the stable names.

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

Next, create a Secret for the database password before you apply the StatefulSet. Never put a real password in plain text in a manifest that you commit to version control. A simple and safe starting point is:

kubectl create secret generic db-secret --from-literal=password='use-a-strong-password-here'

Now create the StatefulSet. The example below runs one PostgreSQL pod, mounts the templated volume at the PostgreSQL data directory, and reads the password from the Secret. Keep replicas at one for a single database unless you have also configured database-level replication. Scaling a StatefulSet to three replicas gives you three pods with three separate volumes, not a replicated database cluster. Replication must be configured inside the database itself, for example with PostgreSQL streaming replication or a database operator.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db
  replicas: 1
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: postgres
          image: postgres:16
          ports:
            - containerPort: 5432
          env:
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db-secret
                  key: password
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi

Apply both manifests with kubectl apply, then check the result. You should see the pod named db-0, not a random name, and a claim named data-db-0. For the full storage background behind this example, including StorageClasses and claim binding, see this guide to PersistentVolumes, PersistentVolumeClaims, and StorageClasses on Kubernetes.

kubectl apply -f db-service.yaml -f db-statefulset.yaml
kubectl get pods -l app=db
kubectl get pvc

Ordered Creation, Scaling, and Deletion

By default, a StatefulSet uses the OrderedReady pod management policy. Pods are created in ordinal order: db-0 must be Running and Ready before db-1 is created, and db-1 must be ready before db-2. This matters for clustered databases, where the first member often initialises the cluster and later members join an existing cluster. If you start all members at once, they may each try to initialise an empty cluster and disagree about the state.

Scaling down works in reverse order. If you scale from three replicas to one, db-2 is deleted first, then db-1, and db-0 remains last. Deleting a StatefulSet does not delete its PersistentVolumeClaims by default. That is a deliberate safety choice: deleting the workload should not silently delete the database. Remove claims manually only when you are certain the data is backed up or no longer needed, using kubectl delete pvc followed by the claim name, and double-check the namespace first.

If your application does not need strict ordering and can start members in parallel, you can set podManagementPolicy to Parallel. Use this only when you understand the application startup behaviour. For most databases, keep the default OrderedReady policy and let Kubernetes enforce the safe order.

Update Strategies and Backups

When you plan kubernetes statefulsets updates, remember that StatefulSet updates are controlled by the updateStrategy field. The RollingUpdate strategy updates pods in reverse ordinal order, starting with the highest ordinal, and waits for each updated pod to be Running and Ready before moving to the next. You can use the partition field to hold back updates: with partition set to 2, only pods with an ordinal of 2 or higher are updated, which lets you test a new image on one pod before rolling it out to the rest. The OnDelete strategy is different: changing the StatefulSet does nothing to running pods until you delete each pod manually, and the replacement pod then uses the new template. OnDelete is useful for databases where you want full manual control over restart timing.

Do not confuse StatefulSet storage with a backup. A PersistentVolume protects you from pod deletion, but it does not protect you from accidental table drops, bad migrations, or storage failures. Back up the database itself with its native tools, such as pg_dump for PostgreSQL or mysqldump for MySQL, store those backups off the cluster, and test a restore at least once. If your StorageClass supports volume snapshots, snapshots are a useful second layer, but they do not replace a tested database backup.

Troubleshooting

When a StatefulSet pod is stuck in Pending, the cause is usually storage or scheduling, not the kubernetes statefulsets controller itself. Run kubectl describe pod for the stuck pod and read the Events section. Common causes are no matching StorageClass, a StorageClass that cannot provision in that zone, insufficient node resources, or a node selector that matches no node. Run kubectl get pvc to see whether the claim is bound. A claim stuck in Pending means the volume was never created, and the pod cannot start without it.

When a pod is stuck in CrashLoopBackOff, check the logs with kubectl logs for that pod name, using the stable name such as db-0. For PostgreSQL, common causes are a wrong password Secret key, a data directory with wrong permissions after a manual volume change, or a missing environment variable. Remember that the Secret key name in secretKeyRef must match the key you created. A typo there gives the pod an empty or missing variable rather than a clear error in the StatefulSet itself.

When scaling seems stuck, remember that ordinals cannot be skipped. You cannot have db-0 and db-2 without db-1, and a new pod will not be created until the previous pod is Ready. If a pod is not becoming Ready, check its readiness probe, its logs, and whether the database is still initialising. Deleting a StatefulSet pod is safe in the StatefulSet model: Kubernetes recreates a pod with the same name and reattaches the same claim, so a delete is often the cleanest way to recover a pod that is wedged after a bad configuration change.

Conclusion

Use a Deployment when any pod can replace any other pod without loss. Use a StatefulSet when identity and data must survive restarts, which is the normal case for databases. A well-planned kubernetes statefulsets deployment gives you predictable behaviour that clustered databases depend on. Build the example above, practise scaling and updating it, verify your backups with a real restore, and you will have a stateful workload you can trust in production. For the official reference, see the Kubernetes StatefulSets documentation.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.