Geavanceerd
Zoeken inHow-to-gidsen
Zo zoek je
  • Typ de taak in je eigen woorden (poort vinden, firewall openen, schijf vol) of plak een foutmelding tussen aanhalingstekens.
  • Kies "Snel antwoord" om alleen de commando's te zien, of een gebied om in één vakgebied te blijven.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

How-to 250Kubernetes · Workloads

How to run a database as a StatefulSet

A Deployment treats Pods as identical and replaceable — wrong for a database, where each instance needs its own disk and a stable name. A StatefulSet gives Pods fixed names (pg-0, pg-1), one PVC each from a template, ordered start and stop, and a headless Service so pg-0.pg always reaches the same instance. This how-to runs a single PostgreSQL instance properly, and says when to use an operator or a managed database instead.

  • 5 Lessen
  • 3 Commando's

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

250.1

The quick answer

postgres.yaml
apiVersion: v1
kind: Service
metadata:
  name: pg
  namespace: data
spec:
  clusterIP: None
  selector: { app: pg }
  ports: [{ port: 5432 }]
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: pg
  namespace: data
spec:
  serviceName: pg
  replicas: 1
  selector:
    matchLabels: { app: pg }
  template:
    metadata:
      labels: { app: pg }
    spec:
      securityContext: { fsGroup: 999 }
      containers:
        - name: postgres
          image: postgres:16
          env:
            - name: POSTGRES_PASSWORD
              valueFrom: { secretKeyRef: { name: pg-auth, key: password } }
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          ports: [{ containerPort: 5432 }]
          readinessProbe:
            exec: { command: ["pg_isready", "-U", "postgres"] }
          resources:
            requests: { cpu: 250m, memory: 512Mi }
            limits: { memory: 1Gi }
          volumeMounts:
            - { name: data, mountPath: /var/lib/postgresql/data }
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: [ReadWriteOnce]
        resources:
          requests: { storage: 20Gi }
kubectl -n data create secret generic pg-auth --from-literal=password="$(openssl rand -base64 24)"
kubectl apply -f postgres.yaml
kubectl -n data get pods,pvc

250.2

Step by step

  1. Headless Service (clusterIP: None) — gives each Pod a DNS name: pg-0.pg.data.svc.cluster.local. Apps connect to that name (or to pg for "any").
  2. volumeClaimTemplates — each Pod gets its own PVC (data-pg-0). When pg-0 is rescheduled, it gets the same PVC back.
  3. PGDATA in a subfolder — the volume root may contain lost+found, which PostgreSQL refuses; a subfolder avoids that.
  4. Password from a Secret (first command) — never in the YAML.
  5. Connect and test:
kubectl -n data exec -it pg-0 -- psql -U postgres -c "SELECT version();"
  1. Backups — a CronJob with pg_dump to object storage, plus volume snapshots; test restores. Deleting the StatefulSet does not delete the PVCs (on purpose); deleting the namespace does.
  2. More than one replica is not replication — replicas: 3 gives three independent empty databases. For primary/replica with failover use an operator (CloudNativePG, Zalando Postgres Operator, Crunchy) — or a managed database (RDS, Azure Database), which is often the better choice for production.
  3. Updates — changing the image rolls Pods one by one from the highest ordinal; for databases check the release notes (major versions need a dump/restore or pg_upgrade).

250.3

Check that it worked

kubectl -n data get pods shows pg-0 Running and 1/1 ready; kubectl -n data get pvc shows data-pg-0 Bound; a table created in pg-0 is still there after kubectl -n data delete pod pg-0 (the Pod comes back with the same name and disk).

250.4

Common problems

ProblemCauseFix
initdb: directory … exists but is not emptylost+found in the volume root.Set PGDATA to a subfolder.
Pod PendingPVC cannot be provisioned.Check the StorageClass; kubectl describe pvc data-pg-0.
Three replicas, different dataStatefulSet does not replicate data.Use an operator or a managed database.
Data lost after deleting the namespacePVCs deleted with it (reclaim Delete).Backups; Retain class; protect the namespace.
Pod stuck Terminating after node failureStatefulSet waits to be sure the old Pod is gone (no two writers).Confirm the node is dead, then force delete the Pod.
App cannot reach pg-0.pgWrong serviceName or namespace.serviceName must match the headless Service; use the full name.

250.5

Go further

1What does a StatefulSet give a database that a Deployment does not?

Stable Pod names, one persistent volume per Pod that comes back after rescheduling, and ordered start and stop.

2Does replicas: 3 in a StatefulSet create a replicated database?

No — it creates three independent instances; replication needs the database's own setup, usually through an operator.

Alle commando's in dit hoofdstuk