Skip to main content

Containers and Kubernetes · Advanced · 24 min

Run PostgreSQL for Snip in a StatefulSet with persistent storage

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Kubernetes 1.37 on kind 0.33 · PostgreSQL 18.7 · Kustomize 5.8.3

You will run PostgreSQL 18 for the Snip API as a one-replica StatefulSet on kind with its own persistent volume, a password Secret made from files, a Job that runs Snip's own schema migration and a DATABASE_URL wired into Snip, and prove that the data outlives the pod.

On this page

So far Snip keeps its links in memory, so every restart, rollout or rescheduled pod forgets them. In this part you give it a real PostgreSQL 18 database inside the cluster. A Deployment is the wrong tool for that: its pods are interchangeable, get random names and share whatever volume you give them. A database needs the opposite. It needs one pod with a name that stays the same, and a disk that belongs to that pod and follows it when it is replaced. That is what a StatefulSet provides.

You will add the database as a Kustomize component, so both overlays from part 2 can pull it in without copying files, create the password as a Secret from files that never appear on a command line, run the snip migrate subcommand you wrote in part 1 as a Kubernetes Job, and give Snip its DATABASE_URL from the same Secret. Then you delete the database pod and check that the data is still there. The hands-on steps apply the dev overlay, which runs in the snip namespace. The last step is an honest look at when you should not run PostgreSQL this way at all.

Step 1 · Check the cluster's storage class

Every pod in the StatefulSet asks for a PersistentVolumeClaim, and the cluster turns each claim into a real volume through a StorageClass. kind ships one called standard, backed by Rancher's local-path provisioner, which creates a folder on the node for each volume. Confirm it is there and that the dev namespace from part 2 exists:

Bash
kubectl get storageclass
kubectl get namespace snip

Check it worked

The first command lists standard (default) with the provisioner rancher.io/local-path, and the second shows snip as Active. If snip is missing, apply the dev overlay as in part 2 first. On a cloud cluster the class has another name (and provisions real disks, which cost money); put that name in storageClassName in the next steps instead of standard.

Keep one fact about kind in mind for the rest of the series: the node is a Docker container, so the volume is a folder inside it. Deleting the kind cluster deletes the database with it.

Step 2 · Create the database password, connection string and Secret

Snip needs a full connection URL, and PostgreSQL needs the password on its own. Generate both into files in a private folder. Each file is created with mode 600 before anything is written to it, so there is no moment when another user can read it. The URL is assembled with cat, so the password is never an argument to a command, and never lands in your shell history or the process list. A hex password is safe to put in a URL without escaping:

Bash
cd ~/snip-demo
install -d -m 700 .secrets
install -m 600 /dev/null .secrets/password
openssl rand -hex 24 | tr -d '\n' >> .secrets/password
install -m 600 /dev/null .secrets/database-url
{ printf 'postgres://snip:'; cat .secrets/password; printf '@snip-db-0.snip-db:5432/snip?sslmode=disable'; } >> .secrets/database-url
grep -qxF '.secrets/' .gitignore 2>/dev/null || echo '.secrets/' >> .gitignore

The host snip-db-0.snip-db is the stable address the StatefulSet will give its first pod: pod snip-db-0, behind the headless Service snip-db. It leaves the namespace out on purpose. Every pod's DNS settings search its own namespace first, so from a pod in snip the name resolves to snip-db-0.snip-db.snip.svc.cluster.local, and the same URL works unchanged on a production cluster that also uses the snip namespace. Snip's static Go binary uses Go's own resolver, which reads those search domains too. sslmode=disable is acceptable for traffic that stays on the cluster network of a local kind cluster. Part 7 limits who can reach the database at all.

Look at the files without printing the password:

Bash
cd ~/snip-demo
ls -l .secrets
wc -c < .secrets/password
sed 's/:[^:@]*@/:********@/' .secrets/database-url; echo

Now create the Secret in snip from the two files. --from-file=key=path reads each value from its file, so it is again never typed:

Bash
cd ~/snip-demo
kubectl create secret generic snip-db -n snip \
  --from-file=password=.secrets/password \
  --from-file=database-url=.secrets/database-url
kubectl describe secret snip-db -n snip

This Secret deliberately stays out of the Kustomize files. A secretGenerator would work, but then kustomize build prints the password into any terminal, log or CI job that renders the manifests.

This part applies only the dev overlay. The prod overlay asks for the same snip-db Secret, so on a production cluster run the same commands there with a separate folder (.secrets/prod) and the production cluster's kubeconfig context. Give production its own password; never copy dev's.

Check it worked

Both files show -rw-------, the password is 48 bytes, and the URL prints with the password masked, as postgres://snip:********@snip-db-0.snip-db:5432/snip?sslmode=disable. kubectl describe secret shows Type: Opaque and, under Data, database-url and password with their sizes in bytes (password: 48 bytes) rather than their values.

Step 3 · Write the database as a Kustomize component

A component is a reusable piece that any overlay can switch on. Putting the database in one keeps the base from part 2 untouched and lets dev and prod share a single definition. Create the folder and its headless Service first. clusterIP: None means the Service gets no virtual IP of its own. Instead, DNS answers with the pod's address, and the StatefulSet uses the Service to give each pod its own DNS name:

Bash
mkdir -p ~/snip-demo/k8s/components/postgres
cd ~/snip-demo/k8s/components/postgres
cat > service.yaml <<'YAML'
apiVersion: v1
kind: Service
metadata:
  name: snip-db
  namespace: snip
  labels:
    app.kubernetes.io/name: snip-db
spec:
  clusterIP: None
  selector:
    app.kubernetes.io/name: snip-db
  ports:
    - name: postgres
      port: 5432
      targetPort: postgres
YAML

Now the StatefulSet. Read it with these points in mind:

  • Like the Service, it sets namespace: snip itself. The next step explains why a component's objects need that.
  • serviceName: snip-db ties the pod names to the headless Service, which gives you snip-db-0.snip-db.
  • volumeClaimTemplates makes one claim per pod, named data-snip-db-0. If the pod is deleted, its replacement gets the same name and attaches the same claim.
  • The image is pinned to postgres:18.7-trixie, the current minor release. From version 18 the official image keeps its data in /var/lib/postgresql/18/docker and expects the volume at /var/lib/postgresql. Mounting one level up means the data sits in a subfolder of the volume, so initdb never meets a non-empty mount point (some disks carry a lost+found folder), and a later major upgrade can put 19/ next to 18/ on the same disk. PGDATA is set explicitly so the path is in the manifest rather than in the image.
  • POSTGRES_PASSWORD_FILE makes the image read the password from the mounted Secret on first start. The password never becomes an environment variable of the database container.
  • fsGroup: 999 with defaultMode: 0440 lets the image's postgres user (group 999) read the Secret file, and nobody else.
  • persistentVolumeClaimRetentionPolicy set to Retain keeps the claim, and the data, even if you delete the whole StatefulSet or scale it to zero.
Bash
cd ~/snip-demo/k8s/components/postgres
cat > statefulset.yaml <<'YAML'
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: snip-db
  namespace: snip
  labels:
    app.kubernetes.io/name: snip-db
spec:
  serviceName: snip-db
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: snip-db
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: Retain
    whenScaled: Retain
  template:
    metadata:
      labels:
        app.kubernetes.io/name: snip-db
    spec:
      terminationGracePeriodSeconds: 60
      securityContext:
        fsGroup: 999
      containers:
        - name: postgres
          image: postgres:18.7-trixie
          ports:
            - name: postgres
              containerPort: 5432
          env:
            - name: POSTGRES_USER
              value: snip
            - name: POSTGRES_DB
              value: snip
            - name: POSTGRES_PASSWORD_FILE
              value: /run/secrets/snip-db/password
            - name: PGDATA
              value: /var/lib/postgresql/18/docker
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql
            - name: credentials
              mountPath: /run/secrets/snip-db
              readOnly: true
          readinessProbe:
            exec:
              command: ["pg_isready", "-h", "127.0.0.1", "-U", "snip", "-d", "snip"]
            periodSeconds: 5
            failureThreshold: 6
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              memory: 512Mi
      volumes:
        - name: credentials
          secret:
            secretName: snip-db
            defaultMode: 0440
            items:
              - key: password
                path: password
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: standard
        resources:
          requests:
            storage: 1Gi
YAML

terminationGracePeriodSeconds: 60 gives PostgreSQL time to finish a clean shutdown when Kubernetes sends it SIGTERM, instead of being killed after the default 30 seconds. The memory limit has no CPU partner on purpose: a CPU limit throttles a database in ways that are hard to see, while a memory limit stops a runaway query from taking the node down.

Check it worked

Bash
ls ~/snip-demo/k8s/components/postgres

The folder holds service.yaml and statefulset.yaml. The component file that ties them together comes in the next step.

Step 4 · Point Snip at the database and switch the component on

Snip reads DATABASE_URL and uses PostgreSQL when it is set, as you built it in part 1. Add a patch that sets the variable on the snip container from the Secret's database-url key. A strategic-merge patch only names what changes, so it adds to the Deployment from part 2 without repeating it:

Bash
cd ~/snip-demo/k8s/components/postgres
cat > snip-database-url.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: snip
spec:
  template:
    spec:
      containers:
        - name: snip
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: snip-db
                  key: database-url
YAML
cat > kustomization.yaml <<'YAML'
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component
resources:
  - service.yaml
  - statefulset.yaml
patches:
  - path: snip-database-url.yaml
YAML

Note the different apiVersion and kind: a component is v1alpha1 Component, not a Kustomization. An environment variable is less private than a mounted file (anyone who can exec into the pod can print it), but it is what Snip reads, and the value itself stays in the Secret.

Switch the component on in both overlays. kustomize edit changes each file for you, so you do not have to merge YAML by hand:

Bash
cd ~/snip-demo/k8s
(cd overlays/dev && kustomize edit add component ../../components/postgres)
(cd overlays/prod && kustomize edit add component ../../components/postgres)
cat overlays/dev/kustomization.yaml

Where the database objects end up follows from the order Kustomize works in. It builds the base first, with the base's own namespace: snip and labels, which touch only the base's objects. Then it adds the component's objects and applies its patch. Last, it runs the overlay's own transformers over everything it now holds. Part 2's overlays set no namespace: of their own, so nothing would place snip-db in a namespace, and kubectl apply would put it in default. That is why service.yaml and statefulset.yaml name namespace: snip themselves. The base's app.kubernetes.io/name: snip label never reaches the database objects either, which is why their selector stays app.kubernetes.io/name: snip-db.

The same order breaks one thing in prod. Part 2's gomemlimit.yaml is a JSON patch that does add on /spec/template/spec/containers/0/env with a one-item list. Back then the container had no env, so add created it. Now the component has already put DATABASE_URL there, and an add on an existing path replaces the whole value, so the prod build would silently drop DATABASE_URL. Change the patch to append to the list instead. The /- at the end of the path means "after the last item", and the value is now a single entry, not a list:

Bash
cd ~/snip-demo/k8s
cat > overlays/prod/gomemlimit.yaml <<'YAML'
- op: add
  path: /spec/template/spec/containers/0/env/-
  value:
    name: GOMEMLIMIT
    value: 230MiB
YAML

The append form needs env to exist already, which the component guarantees for every overlay that switches it on. This is the trade-off of JSON patches that part 2 warned about: they act on exact paths, and a change elsewhere can change what a path means.

Check it worked

Bash
cd ~/snip-demo/k8s
kustomize build overlays/dev | grep -E '^  namespace:' | sort | uniq -c
kustomize build overlays/prod | grep -E 'name: (DATABASE_URL|GOMEMLIMIT)'

The dev kustomization now has a components: list with ../../components/postgres in it, next to the resources:, labels:, images: and configMapGenerator: from part 2 (kustomize edit also rewrites the file in its own key order and indentation, which is expected). The count prints 5 namespace: snip: the ConfigMap, both Services, the Deployment and the StatefulSet. The Namespace object itself carries name: snip instead. The prod build lists both name: DATABASE_URL and name: GOMEMLIMIT.

Step 5 · Render and validate both overlays

Render each overlay and pass it to kubeconform, which checks every object against the Kubernetes 1.37 schemas. -strict also rejects fields that do not exist, such as a misspelt volumeClaimTemplate, which the API server would otherwise drop without a word:

Bash
mkdir -p ~/.cache/kubeconform
cd ~/snip-demo/k8s
for env in dev prod; do
  echo "== $env"
  kustomize build "overlays/$env" | kubeconform -strict -summary -kubernetes-version 1.37.3 -cache ~/.cache/kubeconform
done

Check it worked

Each overlay prints Summary: 6 resources found parsing stdin - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0: part 2's four objects plus the StatefulSet and the snip-db Service. Now find the database wiring in the dev Deployment:

Bash
cd ~/snip-demo/k8s
kustomize build overlays/dev | grep -E '^kind:'
kustomize build overlays/dev | grep -B2 -A4 'name: DATABASE_URL'

The kinds include a StatefulSet and two Service objects (snip and snip-db) alongside your part 2 objects. The second command shows DATABASE_URL with a secretKeyRef naming snip-db and database-url.

Step 6 · Write the migration Job

The database starts empty. Part 1 gave Snip a migrate subcommand for this moment: snip migrate reads DATABASE_URL, runs CREATE TABLE IF NOT EXISTS links (...), prints migrate: schema is up to date and exits. Running it as a Job keeps the schema in the same code that uses it, and a Job is a pod that runs to completion and is retried if it fails.

The Job has two containers in sequence. Snip's distroless image has no shell, so the init container uses the postgres image to wait until the database answers, and the migration never fails just because PostgreSQL is still starting. The main container is the Snip image itself. Its ENTRYPOINT is /snip, so args: ["migrate"] runs /snip migrate:

Bash
mkdir -p ~/snip-demo/k8s/migrate
cd ~/snip-demo/k8s/migrate
cat > job.yaml <<'YAML'
apiVersion: batch/v1
kind: Job
metadata:
  name: snip-migrate
  labels:
    app.kubernetes.io/name: snip-migrate
    app.kubernetes.io/part-of: snip
spec:
  backoffLimit: 3
  activeDeadlineSeconds: 600
  template:
    spec:
      restartPolicy: Never
      initContainers:
        - name: wait-for-db
          image: postgres:18.7-trixie
          command:
            - sh
            - -c
            - until pg_isready -h snip-db-0.snip-db -p 5432 -t 2; do echo waiting for snip-db; sleep 2; done
      containers:
        - name: migrate
          image: snip:0.1.0
          imagePullPolicy: IfNotPresent
          args: ["migrate"]
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: snip-db
                  key: database-url
YAML
cat > kustomization.yaml <<'YAML'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - job.yaml
YAML
kustomize build . | kubeconform -strict -summary -kubernetes-version 1.37.3 -cache ~/.cache/kubeconform

The Job lives in its own kustomization, away from the overlays, for two reasons. Applying an overlay never re-runs a migration by accident. And a Job's pod template cannot be changed once the Job exists, so a Job inside the overlay would make the next kubectl apply fail as soon as its image tag changed. The kustomization sets no namespace; you choose one with -n when you apply it. If you tagged your image differently in part 1, change snip:0.1.0 here.

Check it worked

kubeconform prints Summary: 1 resource found parsing stdin - Valid: 1, Invalid: 0, Errors: 0, Skipped: 0, and ~/snip-demo/k8s/migrate holds job.yaml and kustomization.yaml. You run the Job against the cluster in the next step, once the database is up.

Step 7 · Deploy the database and run the migration

Apply the dev overlay. The StatefulSet creates snip-db-0, the claim data-snip-db-0 is bound to a new volume, and the Snip pod is replaced with one that has DATABASE_URL set:

Bash
cd ~/snip-demo/k8s
kustomize build overlays/dev | kubectl apply -f -
kubectl rollout status statefulset/snip-db -n snip --timeout=180s
kubectl get pvc -n snip

The claim data-snip-db-0 is Bound with capacity 1Gi and class standard. The first start takes longer than later ones, because the image runs initdb and creates the snip role and database. Now run the migration in the same namespace and wait for it:

Bash
cd ~/snip-demo/k8s
kustomize build migrate | kubectl apply -n snip -f -
kubectl wait job/snip-migrate -n snip --for=condition=Complete --timeout=180s
kubectl logs job/snip-migrate -n snip -c migrate

The log is one line ending in migrate: schema is up to date. When a later Snip version changes the schema, delete the finished Job first (kubectl delete job snip-migrate -n snip), set the new tag in job.yaml and apply it again. CREATE TABLE IF NOT EXISTS makes a re-run harmless.

Check it worked

Bash
kubectl get pods -n snip
kubectl logs deployment/snip -n snip | grep 'store:'
kubectl exec -n snip snip-db-0 -- psql -U snip -d snip -c '\dt'

snip-db-0 is 1/1 Running next to the Snip pod, and the snip-migrate-... pod shows Completed. Snip's log says store: postgresql, and \dt lists the table links owned by snip. psql inside the pod connects over the local socket, which the official image trusts, so it does not ask for the password. If snip-db-0 is stuck in ContainerCreating, kubectl describe pod snip-db-0 -n snip usually shows a missing snip-db Secret; create it in snip as in the second step.

Step 8 · Prove the data survives losing the pod

Create a link through Snip's API, so the row is written by the app rather than by hand. Port-forward to the Service in the background, post a link and stop the port-forward:

Bash
kubectl port-forward -n snip svc/snip 8080:80 >/dev/null &
PF=$!
sleep 2
curl -s -X POST -H 'Content-Type: application/json' -d '{"url":"https://kubernetes.io/docs/"}' http://127.0.0.1:8080/links; echo
kill "$PF"

Now note the database pod's unique ID, delete the pod, wait for its replacement and read the table:

Bash
kubectl get pod snip-db-0 -n snip -o jsonpath='{.metadata.uid}{"\n"}'
kubectl delete pod snip-db-0 -n snip
kubectl wait pod/snip-db-0 -n snip --for=create --timeout=60s
kubectl wait pod/snip-db-0 -n snip --for=condition=Ready --timeout=180s
kubectl get pod snip-db-0 -n snip -o jsonpath='{.metadata.uid}{"\n"}'
kubectl exec -n snip snip-db-0 -- psql -U snip -d snip -c "SELECT code, url FROM links;"

kubectl delete waits until the old pod is gone, and --for=create then waits for the StatefulSet to make the new one, so the Ready wait never runs against a pod that does not exist yet.

Check it worked

The curl call printed JSON such as {"code":"k3x9qa","url":"https://kubernetes.io/docs/"}. The two UIDs differ, so this is a new pod, but it has the same name, and the SELECT returns the row with that same code. The StatefulSet recreated snip-db-0 and attached the same claim, data-snip-db-0. Leave the database running: the next parts of the series need it.

Step 9 · Decide whether this database belongs in the cluster

What you have built is a sound single-instance PostgreSQL, and it is right for development, demos and small internal tools. It is not a production database service. Before you rely on it, check what it lacks:

  • No standby. If the node or its disk fails, the database is down until you restore it. The local-path volume is a folder on one node; it cannot move to another node.
  • No backups. Nothing here takes them. At the very least, schedule pg_dump to storage outside the cluster, and practise a restore.
  • Upgrades are yours. Minor releases are a tag change and a restart. Major versions need pg_upgrade or a dump and restore, which this setup does not automate.
  • Tuning and monitoring are yours, from memory settings to connection limits and slow-query logs.

There are two better options when those gaps matter. A managed database from your cloud provider gives you standbys, point-in-time recovery and patching, and Snip only needs a new database-url in its Secret. Check that a region is near your users; for an audience in Africa, a database in a far-away region adds round-trip time to every query, and Snip's redirects make one query per click. An operator such as CloudNativePG runs PostgreSQL inside Kubernetes with replicas, automated failover and backups to object storage, described as one Cluster object. It is a good fit when you must stay on your own clusters, but you then run the operator too.

Check it worked

Write down, in a line each, who restores the database if snip-db-0's node is lost, where the last backup is, and how long Snip may be down. If you cannot fill in all three for an environment, use a managed database or an operator there, and keep this StatefulSet for dev.

Next steps

  • Give Snip startup, readiness and liveness probes, and watch readiness react when you stop PostgreSQL, in /tutorials/keep-snip-healthy-with-probes-and-graceful-shutdown.
  • Learn how claims, volumes and storage classes fit together outside a StatefulSet in /tutorials/store-data-in-kubernetes-with-persistent-volumes-and-claims.
  • Run the same PostgreSQL 18 on a plain Ubuntu server, with remote access closed by default, in /tutorials/install-postgresql-18-on-ubuntu-26-04.
  • Keep the .secrets folder and any Secret YAML out of your repository with /tutorials/keep-secrets-out-of-git.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.