Tutorial · Kubernetes · Docker
Kubernetes basics – Pods, Deployments, Services, Gateway API, ConfigMaps and Secrets, probes, resources, HPA and rolling updates
We run the dumpling-shop application (a NestJS API, an nginx frontend, PostgreSQL and Redis) on Kubernetes and meet the key objects along the way: Pod, Deployment, StatefulSet, Service, Gateway API and Ingress, ConfigMap and Secret, startup/liveness/readiness probes, requests and limits, HPA autoscaling and rolling updates with rollback – with YAML manifests and kubectl sessions.
Kubernetes has a reputation as a tool you cannot learn without a week of documentation. Yet running a typical web application takes a dozen or so concepts – and each of them solves a concrete problem you would have with servers anyway: restarting after a crash, several copies behind one address, per-environment configuration, updates without downtime, more machines under more traffic. In this tutorial you will move the application from the Docker tutorial into a cluster and see why each object exists.
Prerequisites: Docker for developers (the pierogi-api and pierogi-web images), kubectl and a local cluster: kind, minikube, k3d or Kubernetes in Docker Desktop.
- 2 → 10
- API replicas – HPA at 70% CPU relative to the request
- 0
- downtime during updates – `maxUnavailable: 0`, readiness
- 3
- kinds of probes – startup, liveness, readiness
- 1
- deploy command – `kubectl apply -k k8s/`
How a cluster is built
Everything goes through the kube-apiserver: you store the desired state, controllers compare it with the actual state and act (e.g. the ReplicaSet controller creates missing pods), the scheduler assigns pods to nodes, and the kubelet on each node runs containers through containerd and reports their status. In a managed cluster (EKS, GKE, AKS) the provider runs the control plane.
| Object | Used for | In this application |
|---|---|---|
| Pod | the smallest unit: one or more containers sharing an IP | every API, web and redis replica |
| Deployment → ReplicaSet | stateless replicas, rolling updates, rollback | api, web, redis |
| StatefulSet | a stable name (postgres-0) and a volume per replica | postgres |
| Service | a stable DNS name and load balancing across pods | api, web, postgres, redis |
| Gateway + HTTPRoute (or Ingress) | HTTP traffic from outside, routing by path and host | /api → api, / → web |
| ConfigMap / Secret | configuration and sensitive data outside the image | api-config, db-credentials |
| HorizontalPodAutoscaler | replica count driven by metrics | api: 2–10 |
| Namespace | a boundary for names, permissions and quotas | pierogi |
Step 1. A local cluster and images
kind create cluster --name pierogi # or: minikube start / k3d cluster create
docker build -t pierogi-api:1.0.0 --target runtime ./api
docker build -t pierogi-web:1.0.0 --target runtime ./web
kind load docker-image pierogi-api:1.0.0 pierogi-web:1.0.0 --name pierogi # minikube: minikube image load …
kubectl get nodes
In a real cluster you push images to a registry (GHCR, ECR, Artifact Registry) and reference the full path with an immutable tag or a digest in the manifest. A local cluster cannot see the images in your Docker, which is why you load them.
Step 2. Namespace, configuration and a secret
Namespace, ConfigMap and Kustomize
apiVersion: v1
kind: Namespace
metadata:
name: pierogi
labels:
app.kubernetes.io/part-of: pierogi
# Pod Security Admission: reject pods that run as root, privileged, etc.
pod-security.kubernetes.io/enforce: restrictedapiVersion: v1
kind: ConfigMap
metadata:
name: api-config
data:
PORT: "3000"
REDIS_URL: redis://redis:6379
---
apiVersion: v1
kind: ConfigMap
metadata:
name: postgres-init
data:
init.sql: |
CREATE TABLE IF NOT EXISTS menu (id TEXT PRIMARY KEY, name TEXT NOT NULL, price_cents INTEGER NOT NULL);
INSERT INTO menu VALUES ('ruskie', 'Ruskie', 2400), ('meat', 'With meat', 2700), ('spinach', 'Spinach & feta', 2600)
ON CONFLICT (id) DO NOTHING;
# The Secret is NOT stored in git – create it once per environment:
# kubectl -n pierogi create secret generic db-credentials --from-literal=password="$(openssl rand -base64 24)"
# In production: External Secrets Operator / Sealed Secrets (see the production article).# kubectl apply -k . (Kustomize is built into kubectl)
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: pierogi
resources:
- namespace.yaml
- config.yaml
- postgres.yaml
- redis.yaml
- api.yaml
- web.yaml
- hpa.yaml
# - gateway.yaml # after installing a Gateway API controller
labels:
- pairs:
app.kubernetes.io/part-of: pierogikubectl apply -f k8s/namespace.yaml
kubectl -n pierogi create secret generic db-credentials --from-literal=password="$(openssl rand -base64 24)"
kubectl apply -k k8s/
- A ConfigMap holds configuration that differs between environments but is not secret. Changing a ConfigMap does not restart pods – environment variables are read at startup, so after a change run
kubectl rollout restart deployment/api(or add a config checksum to the pod template, as in the production tutorial). - A Secret is just base64-encoded data, not encryption. Don't commit it to the repository – create it with a command or sync it from a secret manager (External Secrets, Sealed Secrets).
- The
pod-security.kubernetes.io/enforce: restrictedlabel makes the cluster reject pods running as root or without security restrictions. All manifests in this tutorial comply. - Kustomize (built into
kubectl -k) assembles manifests and sets the namespace and labels. Per-environment variants are overlays instead of copied files.
Step 3. Data: PostgreSQL as a StatefulSet, and Redis
PostgreSQL (StatefulSet + headless Service) and Redis
# Fine for development and learning. In production prefer a managed database
# (RDS, Cloud SQL, Azure Database) or an operator such as CloudNativePG.
apiVersion: v1
kind: Service
metadata:
name: postgres
spec:
clusterIP: None # headless: DNS "postgres" points straight at the pod
selector: { app: postgres }
ports:
- name: postgres
port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres
replicas: 1
selector:
matchLabels: { app: postgres }
template:
metadata:
labels: { app: postgres }
spec:
securityContext:
runAsNonRoot: true
runAsUser: 70 # "postgres" user in the alpine image
fsGroup: 70
seccompProfile: { type: RuntimeDefault }
containers:
- name: postgres
image: postgres:18-alpine
ports:
- name: postgres
containerPort: 5432
env:
- { name: POSTGRES_DB, value: pierogi }
- { name: POSTGRES_USER, value: pierogi }
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef: { name: db-credentials, key: password }
readinessProbe:
exec:
command: ["pg_isready", "-U", "pierogi", "-d", "pierogi"]
periodSeconds: 5
resources:
requests: { cpu: 100m, memory: 256Mi }
limits: { memory: 512Mi }
securityContext:
allowPrivilegeEscalation: false
capabilities: { drop: ["ALL"] }
volumeMounts:
- { name: data, mountPath: /var/lib/postgresql }
- { name: init, mountPath: /docker-entrypoint-initdb.d, readOnly: true }
- { name: run, mountPath: /var/run/postgresql }
volumes:
- name: init
configMap: { name: postgres-init }
- name: run
emptyDir: {}
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests: { storage: 1Gi }apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
spec:
replicas: 1
selector:
matchLabels: { app: redis }
template:
metadata:
labels: { app: redis }
spec:
securityContext:
runAsNonRoot: true
runAsUser: 999
seccompProfile: { type: RuntimeDefault }
containers:
- name: redis
image: redis:8-alpine
args: ["--save", "", "--appendonly", "no"]
ports:
- { name: redis, containerPort: 6379 }
readinessProbe:
exec:
command: ["redis-cli", "ping"]
periodSeconds: 5
resources:
requests: { cpu: 50m, memory: 64Mi }
limits: { memory: 128Mi }
securityContext:
allowPrivilegeEscalation: false
capabilities: { drop: ["ALL"] }
---
apiVersion: v1
kind: Service
metadata:
name: redis
spec:
selector: { app: redis }
ports:
- { name: redis, port: 6379, targetPort: redis }A StatefulSet gives the pod a stable name (postgres-0) and its own PersistentVolumeClaim that survives restarts and rescheduling. The headless Service (clusterIP: None) makes the name postgres point straight at the pod. That is enough for learning and test environments; a production database is better left to a managed service or an operator (e.g. CloudNativePG) that handles replication, backups and failover.
Step 4. API: a Deployment with probes, resources and a hardened security context
API Deployment and Service
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
labels: { app: api }
spec:
replicas: 2
revisionHistoryLimit: 5
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # one extra pod during the update
maxUnavailable: 0 # never go below the desired number of ready pods
selector:
matchLabels: { app: api }
template:
metadata:
labels: { app: api }
spec:
terminationGracePeriodSeconds: 30
securityContext:
runAsNonRoot: true
runAsUser: 1000 # "node" user from the image
seccompProfile: { type: RuntimeDefault }
containers:
- name: api
image: pierogi-api:1.0.0 # in a real cluster: ghcr.io/<org>/pierogi-api:1.0.0 (immutable tag or digest)
imagePullPolicy: IfNotPresent
ports:
- { name: http, containerPort: 3000 }
envFrom:
- configMapRef: { name: api-config }
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef: { name: db-credentials, key: password }
- name: DATABASE_URL # $(VAR) expands a variable defined above
value: postgres://pierogi:$(POSTGRES_PASSWORD)@postgres:5432/pierogi
startupProbe: # gives a slow start up to 30 × 2 s before liveness kicks in
httpGet: { path: /api/live, port: http }
periodSeconds: 2
failureThreshold: 30
livenessProbe: # "is the process stuck?" → restart the container
httpGet: { path: /api/live, port: http }
periodSeconds: 10
failureThreshold: 3
readinessProbe: # "can it serve traffic?" → in/out of the Service endpoints
httpGet: { path: /api/health, port: http }
periodSeconds: 5
failureThreshold: 2
resources:
requests: { cpu: 100m, memory: 128Mi } # what the scheduler reserves
limits: { memory: 256Mi } # above this the container is OOM-killed
lifecycle:
preStop: # let endpoints/load balancers stop sending traffic before SIGTERM
sleep: { seconds: 5 }
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: ["ALL"] }
---
apiVersion: v1
kind: Service
metadata:
name: api
spec:
selector: { app: api }
ports:
- { name: http, port: 3000, targetPort: http }Three probes, three questions
| Probe | Question | On failure | Our endpoint |
|---|---|---|---|
startupProbe | has the app finished starting? | after failureThreshold – restart; until then the other probes wait | /api/live |
livenessProbe | is the process stuck? | the container is restarted | /api/live (no database!) |
readinessProbe | can it serve traffic right now? | the pod leaves the Service endpoints, no restart | /api/health (database + Redis) |
The most common mistake is a liveness probe that checks the database. When the database has a brief outage, Kubernetes restarts every API pod – and after the restart they still cannot connect. That is why liveness asks only about the process itself, while readiness checks dependencies: a pod without its database stops receiving traffic but is not killed. You can verify it by stopping the database:
$ kubectl -n pierogi scale statefulset postgres --replicas=0 statefulset.apps/postgres scaled $ kubectl -n pierogi get pods -l app=api NAME READY STATUS RESTARTS AGE api-6d9c7b8f5d-7xk2p 0/1 Running 0 12m api-6d9c7b8f5d-qm4zt 0/1 Running 0 12m $ kubectl -n pierogi scale statefulset postgres --replicas=1 # after a moment the pods are back to 1/1
Requests, limits and QoS classes
requests– how much the scheduler reserves for the pod. A pod lands only on a node with that much free capacity; the HPA percentage is also computed against the CPU request.limits.memory– exceeding it kills the container (OOMKilled). A CPU limit does not kill, it throttles – which is why this project does not set one.- The QoS class follows from these settings:
Guaranteed(requests = limits for CPU and memory),Burstable(like our API) orBestEffort(nothing set – first to be evicted when a node runs out of memory).
Other details of the manifest
$(POSTGRES_PASSWORD)insideDATABASE_URL– Kubernetes expands references to variables defined earlier in the same container, so the password stays in the Secret.preStop: sleep 5– before the container receivesSIGTERM, the pod is removed from the endpoints, but kube-proxy and load balancers need a moment to notice. Waiting five seconds prevents 502 errors during updates.securityContext: no root, no privilege escalation, dropped capabilities, a read-only filesystem, a seccomp profile. The Node app writes nothing to disk, soreadOnlyRootFilesystemdoes not get in the way.
Step 5. The frontend and traffic from outside
Frontend Deployment and Service
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
labels: { app: web }
spec:
replicas: 2
selector:
matchLabels: { app: web }
template:
metadata:
labels: { app: web }
spec:
securityContext:
runAsNonRoot: true
runAsUser: 101 # nginx-unprivileged
seccompProfile: { type: RuntimeDefault }
containers:
- name: web
image: pierogi-web:1.0.0
imagePullPolicy: IfNotPresent
ports:
- { name: http, containerPort: 8080 }
readinessProbe:
httpGet: { path: /healthz, port: http }
periodSeconds: 5
livenessProbe:
httpGet: { path: /healthz, port: http }
periodSeconds: 15
resources:
requests: { cpu: 20m, memory: 32Mi }
limits: { memory: 64Mi }
securityContext:
allowPrivilegeEscalation: false
capabilities: { drop: ["ALL"] }
---
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector: { app: web }
ports:
- { name: http, port: 80, targetPort: http }| Service type | Reachable from | When |
|---|---|---|
ClusterIP (default) | inside the cluster | service-to-service traffic – all our Services |
NodePort | a port on every node | testing, older integrations |
LoadBalancer | an external cloud load balancer | a single TCP/UDP service exposed to the world |
| Gateway API / Ingress | one HTTP(S) entry point with routing | many HTTP services under one domain, TLS |
Kubernetes has two APIs for external HTTP traffic. Ingress is older and simpler, and its most popular controller, ingress-nginx, was retired in March 2026 (no new releases or security fixes). Its successor is the Gateway API: roles are separated (the platform team manages the Gateway, application teams manage their HTTPRoutes), and routing, headers and traffic splitting are part of the standard instead of controller-specific annotations.
Gateway API (recommended) and Ingress (alternative)
# Gateway API – the successor of Ingress (ingress-nginx was retired in March 2026).
# Requires a Gateway controller (Envoy Gateway, NGINX Gateway Fabric, Cilium, Istio, cloud LBs…).
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: pierogi
spec:
gatewayClassName: eg # name of the GatewayClass installed by your controller
listeners:
- name: http
protocol: HTTP
port: 80
hostname: pierogi.localtest.me
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: pierogi
spec:
parentRefs:
- name: pierogi
hostnames: ["pierogi.localtest.me"]
rules:
- matches:
- path: { type: PathPrefix, value: /api }
backendRefs:
- { name: api, port: 3000 }
- matches:
- path: { type: PathPrefix, value: / }
backendRefs:
- { name: web, port: 80 }# The classic Ingress API still works and is supported by many controllers
# (Traefik, HAProxy, cloud load balancers). Pick ONE: gateway.yaml or ingress.yaml.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: pierogi
spec:
ingressClassName: traefik
rules:
- host: pierogi.localtest.me
http:
paths:
- path: /api
pathType: Prefix
backend:
service: { name: api, port: { number: 3000 } }
- path: /
pathType: Prefix
backend:
service: { name: web, port: { number: 80 } }Both variants need an installed controller (e.g. Envoy Gateway, NGINX Gateway Fabric, Cilium, Traefik or a cloud load balancer controller). Locally, without a controller, a port forward is enough:
$ kubectl -n pierogi port-forward service/web 8080:80
Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080
$ curl -s localhost:8080/api/menu
{"source":"database","items":[{"id":"ruskie","name":"Ruskie","price_cents":2400},{"id":"spinach","name":"Spinach & feta","price_cents":2600},{"id":"meat","name":"With meat","price_cents":2700}]}Step 6. Rolling update and rollback
Changing the image in a Deployment creates a new ReplicaSet. With maxSurge: 1 and maxUnavailable: 0, Kubernetes adds one new pod, waits for it to pass readiness, removes one old pod – and repeats until done. The number of ready replicas never drops below two.
$ kubectl -n pierogi set image deployment/api api=pierogi-api:1.1.0 deployment.apps/api image updated $ kubectl -n pierogi rollout status deployment/api Waiting for deployment "api" rollout to finish: 1 out of 2 new replicas have been updated... Waiting for deployment "api" rollout to finish: 1 old replicas are pending termination... deployment "api" successfully rolled out $ kubectl -n pierogi rollout history deployment/api deployment.apps/api REVISION CHANGE-CAUSE 1 <none> 2 <none> $ kubectl -n pierogi rollout undo deployment/api deployment.apps/api rolled back
If the new version fails readiness (e.g. a configuration error), the update stalls: the old pods keep serving traffic, and after progressDeadlineSeconds (600 s by default) rollout status reports an error. Then it is rollout undo – or a fix and another deployment.
Step 7. HPA autoscaling
HorizontalPodAutoscaler for the API
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization # % of the CPU *request* (100m) – no requests, no autoscaling
averageUtilization: 70
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # wait 5 min before removing pods (no flapping)Every 15 seconds the HPA fetches CPU usage from metrics-server and computes the replica count: with 2 replicas averaging 188% of their request and a 70% target, it gets ⌈2 × 188 / 70⌉ = 6. Scaling up is fast, while scaling down waits 5 minutes (stabilizationWindowSeconds: 300) so the pod count does not jump on brief traffic dips.
$ kubectl -n pierogi get hpa api --watch NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE api Deployment/api cpu: 4%/70% 2 10 2 9m api Deployment/api cpu: 188%/70% 2 10 2 11m api Deployment/api cpu: 188%/70% 2 10 6 11m api Deployment/api cpu: 64%/70% 2 10 6 12m
The HPA does not work without two things: an installed metrics-server (kind needs it added, minikube has a metrics-server addon) and CPU requests on the container – the percentage is computed against the request. For queue workers it is better to scale on queue length (KEDA), and the node count is grown by a separate autoscaler – both are covered in the production tutorial.
Debugging: where to start
kubectl -n pierogi get pods -o wide # status, restarts, node
kubectl -n pierogi describe pod <pod> # events: image pull, probes, OOMKilled
kubectl -n pierogi logs deploy/api --previous # logs of the previous (restarted) container
kubectl -n pierogi get events --sort-by=.lastTimestamp
kubectl -n pierogi exec -it deploy/api -- sh # only if the image has a shell
| Status | Most common cause |
|---|---|
Pending | no node with free resources (requests too big) or no volume |
ImagePullBackOff | a typo in the image name, no registry access, image not loaded into a local cluster |
CrashLoopBackOff | the app exits at startup – check logs --previous and environment variables |
OOMKilled | the memory limit was exceeded – measure usage and fix the limit or the leak |
Running but 0/1 | readiness fails – a dependency (database, Redis) or a wrong probe path |
Common mistakes
- Liveness depending on the database – a database outage restarts every pod.
- No requests – the scheduler crams pods onto one node, the HPA does not work, and
BestEffortpods die first when memory runs out. - Passwords in a ConfigMap, or a Secret in the repository – a Secret is base64, not encryption.
- One replica "because it's just an API" – every node upgrade or restart means downtime.
kubectl editon a live cluster – a change that is not in the repository disappears at the nextapply. Manifests are the source of truth.- A Service selector that does not match pod labels – a Service without endpoints, and timeouts. Check
kubectl get endpointslices -l kubernetes.io/service-name=api.
Check yourself
Question: The database has a 2-minute outage. The API has a readiness probe that checks the database and a liveness probe that checks only the process. What happens?
- Kubernetes restarts every API pod
- The API pods stop receiving traffic (0/1 READY) but are not restarted, and return to traffic once the database answers
- The Deployment rolls back to the previous version
Question: The HPA shows `cpu: <unknown>/70%` and does not scale. What do you check first?
- Whether `maxReplicas` is greater than 10
- Whether metrics-server is running and the container has a CPU request
- Whether the Service is of type LoadBalancer
Interview question: "How do liveness, readiness and startup probes differ, and how would you configure them for an API?"
Readiness answers whether the pod can serve traffic right now – on failure the pod leaves the Service endpoints but is not restarted; it checks the dependencies needed to handle requests (database, cache). Liveness answers whether the process is stuck – on failure the kubelet restarts the container; it checks only the process itself, never external dependencies, because a database outage would restart every replica. Startup protects slow-starting apps: until it passes, liveness and readiness are not run. For a NestJS API: startup and liveness on a lightweight /live, readiness on /health with the database and Redis, a short periodSeconds for readiness and a gentler one for liveness. Plus a preStop with a short wait and SIGTERM handling, so rolling updates happen without 502 errors.
What next
Kubernetes in production – Helm, RBAC, NetworkPolicy, PDB, KEDA, observability and GitOps
Docker for developers – The images we deploy here: multi-stage, small and rootless
Microservices in NestJS – More services to run in the cluster
Microservices – When splitting into services makes sense