Subscribe

Configuring apps on Kubernetes: ConfigMaps, Secrets, probes and resource limits

Move shorty's settings into a ConfigMap and a Secret, add startup, liveness and readiness probes, and set memory requests and limits on a kind cluster. With the mistakes I hit: config that didn't reload and a liveness probe that restarted every pod.

Configuring apps on Kubernetes: ConfigMaps, Secrets, probes and resource limits

In the previous post shorty ran on a local kind cluster, but with the database password typed straight into the Deployment and no health checks at all. Kubernetes marked each pod ready the moment the process started, and nothing stopped one pod from eating all the memory on the node.

In this blog we will fix those three things: settings in a ConfigMap and a Secret, startup, liveness and readiness probes, and CPU and memory requests and limits. Level is beginner, and you should have the kind cluster from the last post running with Postgres, Redis and shorty deployed. I used kind v0.33.0 with Kubernetes v1.37.0 and kubectl v1.37.2.

A ConfigMap for the boring settings

shorty reads everything from environment variables (PORT, BASE_URL, REDIS_URL, CACHE_TTL, LOG_LEVEL and a few more). The non-secret ones go into a ConfigMap:

apiVersion: v1
kind: ConfigMap
metadata:
  name: shorty-config
data:
  PORT: "8080"
  BASE_URL: http://localhost:8080
  REDIS_URL: redis://redis:6379/0
  CACHE_TTL: 1h
  LOG_LEVEL: info

Values in a ConfigMap are always strings, so PORT needs the quotes, else the apply fails.

A Secret for DATABASE_URL

The database URL has the password in it, so it goes into a Secret. I create it with kubectl and keep the generated file out of git:

kubectl create secret generic shorty-db \
  --from-literal=DATABASE_URL='postgres://shorty:shorty@postgres:5432/shorty?sslmode=disable' \
  --dry-run=client -o yaml > secret.yaml
kubectl apply -f secret.yaml

Have a look at secret.yaml and you'll find the URL as base64. That is encoding, nothing more:

kubectl get secret shorty-db -o jsonpath='{.data.DATABASE_URL}' | base64 -d

Anyone who can read Secrets in the namespace can read the password. What a Secret gives you is a separate object you can lock down with RBAC, plus the option to encrypt Secrets at rest in etcd. On a managed cluster you'd usually fill them from a secret store instead of a YAML file. For a local cluster, kubectl create secret is fine.

The new Deployment

Here is the shorty Deployment with all three changes. I'll go through the pieces below.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: shorty
  labels:
    app: shorty
spec:
  replicas: 3
  selector:
    matchLabels:
      app: shorty
  template:
    metadata:
      labels:
        app: shorty
    spec:
      containers:
        - name: shorty
          image: shorty:v2
          ports:
            - name: http
              containerPort: 8080
          envFrom:
            - configMapRef:
                name: shorty-config
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: shorty-db
                  key: DATABASE_URL
          startupProbe:
            httpGet:
              path: /healthz
              port: http
            periodSeconds: 2
            failureThreshold: 15
          livenessProbe:
            httpGet:
              path: /healthz
              port: http
            periodSeconds: 10
            failureThreshold: 3
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
            periodSeconds: 5
            failureThreshold: 2
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 64Mi

envFrom loads every key of the ConfigMap as an env var. secretKeyRef picks a single key from the Secret. The Service is the same as before, except targetPort: http now uses the port name.

kubectl apply -f configmap.yaml -f shorty.yaml
kubectl rollout status deploy/shorty

Changing a ConfigMap does not restart anything

This is the first trap. With the port-forward from the last post running, I created a link, changed BASE_URL in the ConfigMap and waited over a minute:

kubectl patch configmap shorty-config --type merge -p '{"data":{"BASE_URL":"https://sho.example.com"}}'
curl -s localhost:8080/links/kind
{"code":"kind","url":"https://kind.sigs.k8s.io/","short_url":"http://localhost:8080/kind","clicks":0,"created_at":"2026-11-19T07:35:50.772121Z"}

Still the old short_url. See, env vars are read once, when the container starts. Kubernetes doesn't restart pods when a ConfigMap they use changes. (Files mounted from a ConfigMap do get updated eventually, but env vars never do.) You restart them yourself:

kubectl rollout restart deploy/shorty

After that the same call returned "short_url":"https://sho.example.com/kind". In the packaging post later in this series, Helm and Kustomize both have a way to make this happen on their own, by putting a hash of the config into the pod template.

Three probes, three jobs

Probes actually took me the longest to get right the first time I used Kubernetes, mostly because they look the same and do different things.

  • The startup probe runs first. Until it passes, the other two are switched off. It's for slow starters, so a liveness probe doesn't kill an app that is still warming up. shorty starts in milliseconds, but periodSeconds: 2 with failureThreshold: 15 gives it 30 seconds anyway.
  • The liveness probe asks "is this process stuck?". If it fails failureThreshold times in a row, the kubelet kills the container and starts it again.
  • The readiness probe asks "should this pod get traffic right now?". If it fails, the pod is taken out of the Service. Nothing is restarted.

shorty already has the two endpoints for this. /healthz always returns 200 if the HTTP server is up. /readyz pings Postgres and returns 503 when it can't reach it. That split matters. If liveness checked the database, a database blip would make Kubernetes restart every shorty pod, which fixes nothing and adds a restart storm on top. The Compose healthchecks post has the same idea from the Docker side.

Watching readiness work

I scaled Postgres to zero to see it:

kubectl scale deploy/postgres --replicas=0
kubectl get pods -l app=shorty
NAME                      READY   STATUS    RESTARTS   AGE
shorty-5b9d8f89cd-g2wwp   0/1     Running   0          48s
shorty-5b9d8f89cd-plhsf   0/1     Running   0          41s
shorty-5b9d8f89cd-xzgbx   0/1     Running   0          44s

All three went 0/1 but RESTARTS stayed at 0, which is exactly what we want. The EndpointSlice still listed the three pod IPs, but each one with ready=false, so the Service sent them nothing. The events showed something I didn't expect though:

Warning  Unhealthy  Readiness probe failed: Get "http://10.244.0.17:8080/readyz": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
Warning  Unhealthy  Readiness probe failed: HTTP probe failed with statuscode: 503

The first failure was a timeout, not a 503. The default timeoutSeconds for a probe is 1 second, and the first ping to a Postgres that had just vanished took longer than that. Both count as a failure, so no harm here. But if your readiness check does real work, set timeoutSeconds on purpose.

I scaled Postgres back to 1 and pods went 1/1 within a few seconds. Then GET /links/kind returned a 500 with relation "links" does not exist in the log. Of course. Postgres used an emptyDir, the new pod started with an empty database, and I had to delete and re-run the migration Job again. Readiness was happy because the ping worked. A readiness probe only checks what you tell it to check.

Breaking liveness on purpose

Next I changed the liveness path to one that doesn't exist:

kubectl patch deploy shorty --type json \
  -p '[{"op":"replace","path":"/spec/template/spec/containers/0/livenessProbe/httpGet/path","value":"/health"}]'

A minute later:

NAME                     READY   STATUS    RESTARTS      AGE
shorty-fd4c99bbd-64ksb   1/1     Running   2 (9s ago)    70s
shorty-fd4c99bbd-dcgb7   1/1     Running   2 (12s ago)   73s
shorty-fd4c99bbd-xv4tt   1/1     Running   2 (15s ago)   75s
Warning  Unhealthy  Liveness probe failed: HTTP probe failed with statuscode: 404
Normal   Killing    Container shorty failed liveness probe, will be restarted

What bothered me is that the rollout itself "succeeded". The startup and readiness probes passed, so the Deployment happily replaced all three healthy pods with ones that get killed every 30 seconds. kubectl rollout status will not save you from a bad liveness probe. Watch the RESTARTS column for a few minutes after changing probes. I re-applied shorty.yaml to put it back.

Requests and limits

Requests and limits look alike too, but they work at different times.

Requests are used when the pod is scheduled. The scheduler only places a pod on a node with that much CPU and memory not yet requested by others. It's a reservation, not a cap.

Limits are enforced while the pod runs. Going over the CPU limit means the container gets throttled, it just runs slower. Going over the memory limit means the kernel kills the container. Kubernetes reports that as OOMKilled with exit code 137, and the pod restarts.

That is why the manifest above has a memory limit but no CPU limit. I'm fine with shorty borrowing idle CPU, I'm not fine with it eating the node's memory. The node here has 10 CPUs and 12 GiB so 50m and 32Mi are tiny. I checked real usage from the node with docker exec <node> crictl stats: each shorty container sat at about 3 to 4 MB idle.

To see the kill for real, I deployed a copy of shorty with a 4Mi limit and fired 600 POSTs at it through port-forward:

kubectl create deploy oomtest --image=shorty:v2
kubectl set env deploy/oomtest --from=secret/shorty-db
kubectl set resources deploy/oomtest --limits=memory=4Mi --requests=memory=4Mi
NAME                      READY   STATUS      RESTARTS      AGE
oomtest-f44746dc7-zrvn8   0/1     OOMKilled   2 (50s ago)   51s

It had already been OOMKilled twice during startup, before I sent anything, and the load finished it off. The port-forward died with it. The debugging post goes deeper into how to spot this when you didn't cause it yourself.

QoS classes

The limits also decide the pod's QoS class, which decides who gets evicted first when a node runs short of memory. Guaranteed needs requests equal to limits for both CPU and memory. Burstable is anything with at least one request. BestEffort has none and goes first. With no CPU limit, shorty is Burstable:

kubectl get pod -l app=shorty -o jsonpath='{.items[0].status.qosClass}'

GOMEMLIMIT

One Go specific tip. The Go garbage collector doesn't know about the container limit, so it can let the heap grow past it before collecting. Since Go 1.19 you can set GOMEMLIMIT, and the downward API can fill it from the limit:

            - name: GOMEMLIMIT
              valueFrom:
                resourceFieldRef:
                  resource: limits.memory
                  divisor: "1"

I checked it from a debug container and the process saw GOMEMLIMIT=67108864, exactly 64Mi. That's the full limit, so for a busy service I'd rather hard-code something around 90% of it, like 56MiB, and leave the GC some room.

That's it. All the files are in the code folder: configmap.yaml, secret.yaml (generated, not for git) and shorty.yaml. If you want the container itself hardened as well, the distroless and non-root post pairs well with this one.