Skip to content

Run PostgreSQL

This assumes you can already reach your cluster with kubectl (see the kubectl quickstart).

You’ll deploy a single PostgreSQL instance in its own namespace, backed by persistent storage so its data survives pod restarts. The cluster’s default StorageClass provisions the volume for you.

Create a dedicated namespace:

Terminal window
kubectl create namespace postgres

Deploy the database, its storage, and a Service into the namespace:

Terminal window
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Secret
metadata:
name: postgres
namespace: postgres
stringData:
POSTGRES_PASSWORD: change-me
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: postgres
namespace: postgres
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres
namespace: postgres
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres
key: POSTGRES_PASSWORD
# Subdir keeps initdb off the volume's lost+found.
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
ports:
- containerPort: 5432
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumes:
- name: data
persistentVolumeClaim:
claimName: postgres
---
apiVersion: v1
kind: Service
metadata:
name: postgres
namespace: postgres
spec:
selector:
app: postgres
ports:
- port: 5432
targetPort: 5432
EOF

This Service is ClusterIP, so the database is only reachable from inside the cluster. On a single-tenant skube cluster that’s the safe default: keep your app and database in the cluster and connect over the Service with no TLS.

If you need to reach it from outside the cluster:

  • For occasional access, prefer kubectl port-forward -n postgres service/postgres 5432:5432 over a public endpoint. It tunnels through the API server and exposes nothing.
  • To expose it for real, enable PostgreSQL’s own TLS (ssl = on with a cert and key). The Ingress and Gateway guides are HTTP-only and don’t apply to the Postgres wire protocol.
  • Use a strong password, not change-me, and rotate the secret if it leaks.

Check it’s accepting queries:

Terminal window
kubectl exec -n postgres deploy/postgres -- psql -U postgres -c "SELECT version();"

Open an interactive psql shell inside the pod:

Terminal window
kubectl exec -n postgres -it deploy/postgres -- psql -U postgres

From there, \l lists databases and \dt lists tables in the current one.

Other workloads in the cluster connect with this URI (<password> is the value from the secret above):

postgresql://postgres:<password>@postgres.postgres.svc.cluster.local:5432/postgres

Delete the namespace to remove everything at once:

Terminal window
kubectl delete namespace postgres

This destroys the database’s data along with it.