Config, secrets, storage & debugging
The same image should run in every environment, with settings, passwords and data supplied from outside. This chapter covers ConfigMaps, Secrets and persistent storage, then the four pod errors you'll meet most often and the exact commands that explain each one.
ConfigMaps
A ConfigMap holds non-secret settings as key-value pairs. Create it from the command line or from YAML:
$ kubectl create configmap web-config \
--from-literal=LOG_LEVEL=info \
--from-file=app.yaml # key = file name, value = file contents
$ kubectl create configmap web-env --from-env-file=web.env # KEY=value lines
$ kubectl get configmap web-config -o yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: web-config
data:
LOG_LEVEL: info
app.yaml: |
port: 3000
cache: true
Secrets
$ kubectl create secret generic db-cred \
--from-literal=username=app \
--from-literal=password='S3cr3t!'
$ kubectl get secret db-cred -o jsonpath='{.data.password}'
UzNjcjN0IQ==
$ echo 'UzNjcjN0IQ==' | base64 -d
S3cr3t!
That's the important lesson: Secret values are only base64-encoded, not encrypted. Anyone allowed to read Secrets in the namespace can decode them in one command. In YAML, data: expects base64 (echo -n 'S3cr3t!' | base64, where -n avoids encoding a newline) and stringData: takes plain text. To actually protect them: restrict access with RBAC, enable encryption at rest for etcd (off by default in a self-managed cluster), and never commit Secret YAML to git; use Sealed Secrets, SOPS or the External Secrets Operator instead.
Using them in a pod
apiVersion: v1
kind: Pod
metadata:
name: web
spec:
containers:
- name: web
image: demee/app:1.1
env:
- name: LOG_LEVEL
valueFrom:
configMapKeyRef:
name: web-config
key: LOG_LEVEL
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-cred
key: password
volumeMounts:
- name: config
mountPath: /etc/web # file appears as /etc/web/app.yaml
readOnly: true
volumes:
- name: config
configMap:
name: web-config
items:
- key: app.yaml
path: app.yaml
envFrom with a configMapRef or secretRef imports every key at once. Secrets can be mounted as files too (secret: {secretName: db-cred}). One behaviour to remember: environment variables are read once, at container start. Edit the ConfigMap and running pods keep the old values until kubectl rollout restart deployment/web. Mounted files do update in place after a short delay (except when mounted with subPath).
Persistent storage: PVC and StorageClass
A pod's filesystem is lost when the pod is replaced. For data that must survive, the pod uses a PersistentVolumeClaim (PVC): a request for storage. A StorageClass describes a kind of storage (a cloud SSD, a local path) and creates a matching PersistentVolume (PV) automatically when a claim appears.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: uploads
spec:
accessModes:
- ReadWriteOnce # mountable by one node at a time
storageClassName: standard # omit to use the cluster's default class
resources:
requests:
storage: 5Gi
$ kubectl get storageclass # the default one is marked "(default)"
$ kubectl get pvc # STATUS should become Bound
In the pod spec: volumes: [{name: uploads, persistentVolumeClaim: {claimName: uploads}}] plus a volumeMounts entry. Worth knowing:
- Access modes:
ReadWriteOnceis what most block storage supports;ReadWriteMany(many nodes at once) needs shared storage such as NFS or a cloud file service. A 3-replica Deployment sharing one RWO claim fails once pods land on different nodes. - Many classes use
WaitForFirstConsumer: the PVC staysPendinguntil a pod uses it. That's normal. - Dynamically created volumes usually have reclaim policy
Delete: delete the PVC and the disk and its data are gone.
StatefulSets, briefly
Databases need more than a Deployment gives them. A StatefulSet gives each pod a stable name (db-0, db-1), starts them in order, and through volumeClaimTemplates gives each pod its own PVC that follows it when it's rescheduled. It needs a headless Service named in serviceName, which gives each pod a DNS name like db-0.db.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: db
spec:
serviceName: db
replicas: 1
selector:
matchLabels:
app: db
template:
metadata:
labels:
app: db
spec:
containers:
- name: postgres
image: postgres:16
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: db-cred
key: password
- name: PGDATA # subfolder: some disks have lost+found at the root
value: /var/lib/postgresql/data/pgdata
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi
Deleting or scaling down a StatefulSet leaves its PVCs behind by default, so the data isn't lost by accident.
Debugging: the three commands
$ kubectl get pods # STATUS and RESTARTS
$ kubectl describe pod web-7c9d8f6b5-x2kq9 # config, Last State, and Events at the bottom
$ kubectl logs web-7c9d8f6b5-x2kq9 --previous # output of the crashed container
$ kubectl get events --sort-by=.metadata.creationTimestamp # everything, in order
Plain kubectl logs shows the current container, which may have just restarted and printed nothing useful yet. --previous shows the one that died.
| Status | What it means | Where to look | Typical fix |
|---|---|---|---|
| Pending | The scheduler can't place the pod on any node | describe pod events: 0/3 nodes are available: 3 Insufficient cpu, or unbound immediate PersistentVolumeClaims | Lower requests, add nodes, fix the PVC or the nodeSelector/taints |
| ImagePullBackOff / ErrImagePull | The node can't download the image | describe pod events: not found, pull access denied, 401 Unauthorized | Fix the name/tag; for private registries add imagePullSecrets |
| CrashLoopBackOff | The container keeps starting and exiting; restarts wait longer each time (up to 5 minutes) | logs --previous; describe shows Last State: Terminated with its exit code | Fix the app error, missing config, or a too-strict liveness probe |
| OOMKilled | The container used more memory than its limit | describe pod: Reason: OOMKilled, Exit Code: 137; kubectl top pod | Raise limits.memory or fix the leak |
| CreateContainerConfigError | A referenced ConfigMap or Secret (or key) doesn't exist | describe pod: e.g. secret "db-cred" not found | Create it in the same namespace, check the key name |
An OOMKilled container often shows as CrashLoopBackOff in kubectl get pods; the real reason is in Last State:
$ kubectl describe pod web-7c9d8f6b5-x2kq9
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: OOMKilled
Exit Code: 137
For a private registry, create the pull secret once and reference it from the pod spec:
$ kubectl create secret docker-registry regcred \
--docker-server=ghcr.io --docker-username=demee --docker-password=<token>
# in the pod spec:
# imagePullSecrets:
# - name: regcred
And when the image has no shell for kubectl exec, attach a temporary debug container that shares the app container's processes:
$ kubectl debug -it web-7c9d8f6b5-x2kq9 --image=busybox:1.36 --target=web