Kubernetes Config, Secrets & Storage: ConfigMaps, Secrets, ESO, PV/PVC, CSI, Database Operators
"Kubernetes Secrets are, by default, stored unencrypted in the API server's underlying data store (etcd). Anyone with API access can retrieve or modify a Secret, and so can anyone with access to etcd." — Kubernetes documentation, Secrets
Summary: Kubernetes separates what a container needs from the image that runs it: settings arrive through ConfigMaps, credentials through Secrets (or straight from Vault and cloud secret managers through External Secrets Operator or the Secrets Store CSI driver), and durable data through PersistentVolumeClaims that a StorageClass and a CSI driver turn into real disks. Almost every production incident in this area comes from not knowing when a change is seen (env vars never, mounted files after the kubelet sync period, subPath never), who can read a Secret (anyone who can create a Pod in the namespace), or what happens to the disk when a claim is deleted. Focus: ConfigMaps (env vs envFrom vs mounted files, configMapKeyRef, immutable ConfigMaps, update propagation and the kubelet sync period, the subPath caveat); Secrets (types Opaque, kubernetes.io/tls, kubernetes.io/dockerconfigjson and others, base64 is not encryption, encryption at rest with EncryptionConfiguration and a KMS provider, RBAC for secrets, secretKeyRef vs mounted secret, environment variables vs files, immutable Secrets); External Secrets Operator (SecretStore, ExternalSecret), the Secrets Store CSI Driver (Vault, AWS, GCP, Azure providers), Sealed Secrets and SOPS for GitOps secrets; config reload (checksum annotation, Reloader, hot reload in the app); volumes (emptyDir, hostPath dangers, projected volume, downwardAPI); PersistentVolume, PersistentVolumeClaim, StorageClass, dynamic provisioning and the provisioner, volumeBindingMode WaitForFirstConsumer and topology, access modes (ReadWriteOnce, ReadOnlyMany, ReadWriteMany, ReadWriteOncePod), reclaimPolicy Retain Delete, volume expansion, VolumeSnapshot and clones, the CSI driver split into node plugin controller plugin with sidecars; StatefulSet volumeClaimTemplates and retention; databases on Kubernetes with operators (CloudNativePG, Percona Operator, Zalando postgres-operator), managed database vs in-cluster, backups to object storage, failover, PodDisruptionBudget for databases, local PV; a preview of Redis, RabbitMQ and Kafka operators; the Go service doing Go config loading with env vars plus an fsnotify file watch (and a viper preview), and the Laravel app (Laravel .env from Secret, config:cache implications, storage volume vs S3 for uploads). Learning goal: Wire a Go service and a Laravel app to ConfigMaps and Secrets so that every value has a known update path; choose between plain Secrets, ESO, the CSI driver, Sealed Secrets and SOPS for a given team; turn on encryption at rest and least-privilege RBAC; pick a StorageClass, access mode and reclaim policy that will not lose data or deadlock a rollout; and decide when a database belongs in the cluster behind an operator and when it belongs in a managed service.
This is the third chapter of the Kubernetes group. Pods, probes, Deployments and the StatefulSet controller itself are in Kubernetes Workloads; the control plane, etcd and the kubelet as components are in Kubernetes Architecture & Setup; ServiceAccounts, Roles and admission policy in general are in Kubernetes Security; Pod Security and image hardening in Container Security; Helm values and Kustomize generators that render these manifests in Packaging for Kubernetes; Argo CD and Flux, which apply them from Git, in GitOps; Docker volumes and bind mounts on one host in Running Containers. The architectural view of why an organisation runs Kubernetes is Containers & Kubernetes, and secret-scanning, incident handling and compliance live in Secure SDLC & Incident Response. The database theory behind the operators is in Replication, Read Replicas & Failover and Backup, PITR & Disaster Recovery; environment variables in Go are in CLI Flags, Environment Variables & Logging, and uploads to S3 from Go in File Uploads, S3 & CDN.
Facts on this page were checked against the Kubernetes documentation as published for the current release line (latest release 1.37.2, 13 October 2026, per kubernetes.io/releases) and the project documentation of each tool on 2026-11-29. No cluster was started for this chapter: every kubectl command in the lab is expected, not run; the Go code and its file-watch behaviour were run on the host.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why config, secrets and storage are separate objects | Why it exists |
| Versions: immutable objects, KMS v2, RWOP, snapshots, CSI | Where it comes from |
env, envFrom, configMapKeyRef, mounted ConfigMap, immutable | ConfigMaps |
| When does a change reach the Pod; kubelet sync period; subPath | Update propagation |
Secret types, base64, size, stringData | Secrets |
EncryptionConfiguration, providers, KMS v2 | Encryption at rest |
| Who can read a Secret | RBAC for secrets |
secretKeyRef or a mounted file | Environment variables vs files |
External Secrets Operator: SecretStore, ExternalSecret | ESO |
| Secrets Store CSI Driver and providers | Secrets Store CSI |
| Sealed Secrets, SOPS, secrets in Git | GitOps secrets |
| Checksum annotation, Reloader, hot reload | Config reload |
emptyDir, hostPath, projected, downwardAPI | Pod volumes |
| PV, PVC, binding, phases | PersistentVolumes and claims |
StorageClass, provisioner, WaitForFirstConsumer, topology | StorageClass and dynamic provisioning |
| RWO, ROX, RWX, RWOP | Access modes |
| Retain, Delete, Recycle | Reclaim policy |
| Growing a volume | Volume expansion |
VolumeSnapshot, clones | Snapshots and clones |
| Controller plugin, node plugin, sidecars | CSI architecture |
volumeClaimTemplates, PVC retention | StatefulSet storage |
| Local disks | Local PV |
| CloudNativePG, Percona, Zalando, managed vs in-cluster | Databases on Kubernetes |
| Redis, RabbitMQ, Kafka operators | Other stateful operators |
| Kubelet timing, atomic writer, phases, knobs, errors | Mechanics |
| Code | Go, Laravel |
| Rotations, migrations, restores | Solving the classic problems |
| Which secret tool, which reload, which storage, which database | Choosing |
| From one Pod to many clusters | In architecture |
| Commands with expected output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The objects (core API unless marked CRD).
| Object | Holds | Scope | Size / limit | Plain words |
|---|---|---|---|---|
| ConfigMap | Non-secret key/value pairs, whole files (data, binaryData) | Namespace | "cannot exceed 1 MiB" | Settings sheet next to the app |
| Secret | Credentials, keys, tokens (data base64, stringData plain on write) | Namespace | "limited to 1MiB" | Same shape as a ConfigMap, a bit more protection |
| PersistentVolumeClaim (PVC) | A request: size, access mode, StorageClass | Namespace | Storage quota | "I need 20 GiB that one node can write" |
| PersistentVolume (PV) | One real piece of storage and how to reach it | Cluster | The disk's size | The disk, as Kubernetes sees it |
| StorageClass | Provisioner, parameters, reclaim policy, binding mode, expansion | Cluster | - | A menu item: "gp3, encrypted, Retain" |
| VolumeSnapshot / VolumeSnapshotContent / VolumeSnapshotClass | Point-in-time copy of a PVC | Namespace / cluster / cluster (CRDs) | Driver-dependent | PVC/PV/StorageClass, but for snapshots |
| CSIDriver, CSINode, VolumeAttachment | Driver capabilities, per-node driver info, attach state | Cluster | - | Plumbing the CSI sidecars and kubelet use |
| ExternalSecret, SecretStore, ClusterSecretStore | What to fetch from which external store (ESO CRDs) | Namespace / cluster | - | "Copy prod/orders-db from Vault into Secret orders-db" |
| SecretProviderClass | What the Secrets Store CSI driver mounts (CRD) | Namespace | - | "Mount these Vault paths as files" |
| SealedSecret | Ciphertext only the in-cluster controller can decrypt (CRD) | Namespace | - | A Secret safe to commit |
How a value reaches the container, and when it changes.
| Delivery | Manifest field | Seen by the process | After an edit | Typical use |
|---|---|---|---|---|
| One env var from a ConfigMap | env[].valueFrom.configMapKeyRef | os.Getenv, $_ENV | Never; needs a new Pod | PORT, APP_ENV |
| All keys as env vars | envFrom[].configMapRef / secretRef | Environment | Never; needs a new Pod | Laravel-style settings |
| One env var from a Secret | env[].valueFrom.secretKeyRef | Environment | Never; needs a new Pod | Legacy apps that only read env |
| Mounted ConfigMap | volumes[].configMap + volumeMounts | Files, one per key | Updated in place, "eventually" | Hot-reloadable settings, config files |
| Mounted secret | volumes[].secret | Files on tmpfs | Updated in place, "eventually" | Passwords, TLS keys, tokens |
subPath mount of one key | volumeMounts[].subPath | One file in an existing dir | Never | nginx.conf into /etc/nginx (with a rollout plan) |
| Projected volume | volumes[].projected.sources | Files from several sources | ConfigMap/Secret parts update; token rotates | Token + labels + config in one dir |
| Downward API | fieldRef / resourceFieldRef | Env or files | Env never; some files update (labels, annotations) | Pod name, namespace, limits |
| Secrets Store CSI | volumes[].csi + SecretProviderClass | Files on tmpfs | Only with rotation enabled (alpha) | Vault / cloud secrets without a Secret object |
| Immutable ConfigMap or Secret | immutable: true | Either way | Cannot be edited: new name + rollout | High-scale clusters, safe rollouts |
Pod volume types you will meet.
| Type | Lives as long as | Backed by | Danger / note |
|---|---|---|---|
emptyDir | The Pod on that node | Node disk, or RAM with medium: Memory | RAM use counts against the container memory limit |
configMap, secret, downwardAPI, projected | The Pod | kubelet-written files (Secret on tmpfs) | Read-only; subPath freezes them |
hostPath | The node | The node's filesystem | "presents many security risks"; avoid outside node agents |
persistentVolumeClaim | The claim, not the Pod | Whatever the PV is (CSI disk, NFS, local) | Access mode and zone decide where the Pod may run |
csi (inline / ephemeral) | The Pod | A CSI driver (Secrets Store, image or scratch drivers) | Driver must support ephemeral mode |
ephemeral (generic ephemeral volume) | The Pod | A PVC created and deleted with the Pod | Uses a StorageClass; useful for big scratch space |
Access modes and reclaim policies.
| Setting | Value | Meaning |
|---|---|---|
| Access mode | ReadWriteOnce (RWO) | Read-write by a single node (several Pods on that node may still share it) |
| Access mode | ReadOnlyMany (ROX) | Read-only by many nodes |
| Access mode | ReadWriteMany (RWX) | Read-write by many nodes (file systems: EFS, Filestore, Azure Files, CephFS, NFS) |
| Access mode | ReadWriteOncePod (RWOP) | Read-write by a single Pod in the whole cluster; CSI only; stable since v1.29 |
| Reclaim policy | Delete | Deleting the PVC deletes the PV and the cloud disk; default for dynamically provisioned volumes |
| Reclaim policy | Retain | PV becomes Released; data and disk stay until an admin cleans up |
| Reclaim policy | Recycle | Deprecated rm -rf; only nfs and hostPath |
Why it exists
An image should be the same bytes in staging and production; only the settings, the credentials and the data differ. The Kubernetes ConfigMap page states the goal directly: "Use a ConfigMap for setting configuration data separately from application code", so you can "fetch a container image running in the cloud and debug the exact same code locally if needed." Credentials need the same separation plus protection, which is why Secret is a separate kind even though it has the same shape. Storage is a different problem again: the PersistentVolume page opens with "Managing storage is a distinct problem from managing compute instances", and splits it into a claim that an application writes (PVC) and a volume that an administrator or a provisioner supplies (PV), with a StorageClass in between so application teams never type a cloud disk ID.
| Simpler choice | Richer choice | What you buy | What you pay |
|---|---|---|---|
| Values baked into the image | ConfigMap and Secret per environment | One image for every environment | Another object to version and roll out |
envFrom everything | Mounted files for what changes | Hot reload, rotation without restart | The app must watch files and re-read |
| Plain Secret in Git | Sealed Secrets or SOPS ciphertext | Git stays the source of truth, safely | Key management, a controller or plugin |
| Secret copied by hand | ESO or the Secrets Store CSI driver | One source of truth (Vault, cloud), rotation | An operator or DaemonSet to run, cloud IAM wiring |
| Default (no) encryption at rest | EncryptionConfiguration with KMS v2 | etcd backups no longer leak Secrets | KMS plugin, key rotation process |
hostPath or one big shared disk | PVC + StorageClass + CSI | Portable, zone-aware, snapshot-able storage | Must understand access modes and reclaim |
| Database in the cluster by hand (StatefulSet) | Operator (CloudNativePG) or managed service | Failover, backups, upgrades automated | Operator to learn, or a cloud bill and less control |
The analogy used through this page: a serviced office building. The ConfigMap is the notice board in your office: anyone in the room can read it, and when facilities pin up a new notice you see it the next time you look (a mounted file), unless you photocopied it on your first day (an environment variable) or framed one page (a subPath). A Secret is the key cabinet: same building, but you want a lock (RBAC), and you do not want the building's archive (etcd backups) to keep readable copies (encryption at rest). An external secret store is the bank vault across the road; ESO is the courier who refills the key cabinet on a schedule, the CSI driver hands the key to you personally at the door. Storage is the rented storage unit: the PVC is your rental request ("20 square metres, one key-holder"), the StorageClass is the price list, the provisioner builds the unit, the PV is the unit itself, and the reclaim policy says whether the unit is emptied and demolished (Delete) or locked and left for the manager (Retain) when your contract ends.
Three common misunderstandings, up front
- "Secrets are encrypted." They are base64-encoded. The Secret page says the
authvalue of a docker config "is base64 encoded; it is obscured but not secret", and the store is plain text unless the API server has an encryption config. See Secrets and Encryption at rest. - "I updated the ConfigMap, so the app has the new value." Environment variables are resolved when the container starts: "ConfigMaps consumed as environment variables are not updated automatically and require a pod restart." Mounted files catch up later; subPath mounts never do. See Update propagation.
- "ReadWriteOnce means one Pod." It means one node: "ReadWriteOnce access mode still can allow multiple pods to access (read from or write to) that volume when the pods are running on the same node." One Pod is ReadWriteOncePod. See Access modes.
Where it comes from
| When | What happened | Source |
|---|---|---|
| Kubernetes 1.13 | CSI goes GA (CSI spec v1.0.0); storage drivers move out of the Kubernetes tree | kubernetes-csi docs, release table |
| 2015 / 2023 | SOPS starts at Mozilla in 2015 and is donated to the CNCF as a Sandbox project in 2023 | SOPS README |
| v1.18 | Raw block volumes and volumeMode stable | PersistentVolumes page feature states |
| v1.19 | immutable field available on ConfigMaps and Secrets; in-tree AWS EBS driver deprecated (removed in v1.27) | ConfigMap page; StorageClass page |
| v1.20 | VolumeSnapshot stable (CRDs plus snapshot controller, CSI only) | PersistentVolumes / Volume Snapshots pages |
| v1.21 | Immutable Secrets and ConfigMaps stable | ConfigMap and Secret pages |
| v1.24 | Volume expansion, CSI expansion and resizing in-use PVCs stable | PersistentVolumes page |
| v1.28 | KMS v1 deprecated; retroactive default StorageClass assignment stable | Encrypt data / KMS pages; PersistentVolumes page |
| v1.29 | KMS v2 stable; ReadWriteOncePod stable | Encrypt data page; PersistentVolumes page |
| v1.32 | StatefulSetAutoDeletePVC (PVC retention policy) stable (alpha 1.23, beta 1.27) | feature-gate reference |
| v1.33 | HonorPVReclaimPolicy stable: a Delete reclaim policy is honoured "irrespective of PV-PVC deletion ordering" (finalizers since v1.31; the gate is later removed) | feature-gate reference |
| v1.34 | VolumeAttributesClass stable (change IOPS/throughput of a bound volume; gate locked on from v1.36) | feature-gate reference |
| CloudNativePG 1.26 → 1.32 | Native Barman object-store backups deprecated in favour of the Barman Cloud plugin (CNPG-I), removed from 1.32.0 | CloudNativePG backup docs |
| 13 Oct 2026 | Kubernetes 1.37.2 and 1.36.6 released (the versions this page was checked against) | kubernetes.io/releases |
Two lineages meet in this chapter. Kubernetes' own objects (ConfigMap, Secret, PV, PVC, StorageClass) have been in the core API for years and change slowly; the secret tooling around them (ESO, the Secrets Store CSI driver, Sealed Secrets, SOPS) and the database operators are separate projects with their own release cadence and their own API groups (external-secrets.io/v1, secrets-store.csi.x-k8s.io/v1, bitnami.com/v1alpha1, postgresql.cnpg.io/v1). Storage moved the other way: the in-tree cloud volume plugins were removed one by one (the StorageClass page: "The AWSElasticBlockStore in-tree storage driver was deprecated in the Kubernetes v1.19 release and then removed entirely in the v1.27 release"), so every cloud disk today is a CSI driver.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product or platform does, and the fix.
ConfigMaps: env, envFrom, configMapKeyRef, mounted files, immutable Must-know
In plain words: A ConfigMap is a named bag of strings in one namespace. A Pod can turn some or all of them into environment variables, or have them appear as files in a directory.
Common misunderstanding: "A ConfigMap is a safe place for a database URL with the password in it." The page is blunt: "ConfigMap does not provide secrecy or encryption." Anything with a credential goes in a Secret (or never into the cluster at all, see ESO).
Definition: A ConfigMap has data (UTF-8 strings) and binaryData (base64), no spec; keys "must consist of alphanumeric characters, -, _ or .", and "The data stored in a ConfigMap cannot exceed 1 MiB." A Pod can reference only ConfigMaps in its own namespace. Three consumption forms:
env[].valueFrom.configMapKeyRefpicks one key and may rename it; "Other keys from the ConfigMap data are not copied into the environment."envFrom[].configMapRefimports every key; "The envFrom field instructs Kubernetes to create environment variables from the sources nested within it." Keys that break the env-name rules are skipped: "If any keys do not meet the rules, those keys are not made available to your container, though the Pod is allowed to start." (The rules are loose today: names may use "any printable ASCII characters except '='".) An optionalprefixis prepended to each name.- A
configMapvolume projects each key as a file (all keys, or theitemsyou list, with optionalpathandmode). A missing ConfigMap blocks the Pod unless the reference isoptional: true.
An immutable ConfigMap (immutable: true, stable since v1.21) "protects you from accidental (or unwanted) updates that could cause applications outages" and "improves performance of your cluster by significantly reducing load on kube-apiserver, by closing watches for ConfigMaps marked as immutable." The flag is one-way: "You can only delete and recreate the ConfigMap."
kubectl apply -f k8s/configmap.yaml, then a Pod that uses orders-env and orders-config starts
1 scheduler binds the Pod to node-b
2 kubelet on node-b fetches orders-env and orders-config (watch-based cache by default)
3 container runtime (containerd or CRI-O, via CRI) creates the container with PORT=8080 CONFIG_DIR=... from envFrom
4 kubelet writes orders-config keys as files under the volume dir, mounts it at /etc/orders/config
5 process starts: os.Getenv("PORT") -> "8080"; reads /etc/orders/config/log_level -> "info"
6 later edit of orders-env: no effect on this container; edit of orders-config: files change in placeReal scenarios:
- A team stores
APP_DEBUG=truein a ConfigMap shared by staging and production because both namespaces copied the same manifest; one ConfigMap per environment (Kustomize overlay or Helm values) prevents it. - A key named
feature.checkout-v2imported withenvFromarrives in the environment (current Kubernetes accepts names of "any printable ASCII characters except '='"), but a shell entrypoint cannot expand it as a variable and a framework that maps env to settings ignores it; name keys like variables (FEATURE_CHECKOUT_V2). - A 3 MB GeoIP database put into a ConfigMap is rejected; it belongs in the image, an init container download, or a volume.
- Ten thousand Pods mounting the same mutable ConfigMap keep ten thousand watches open on the API server; immutable, versioned ConfigMaps close them.
| Product / tool | How ConfigMaps are produced or consumed |
|---|---|
kubectl create configmap --from-literal / --from-file / --from-env-file | Imperative creation; --dry-run=client -o yaml to commit the result |
Kustomize configMapGenerator | Appends a content hash to the name, so a change produces a new name and a rollout |
| Helm | Templates data from values; pair with a checksum annotation for rollouts |
| Argo CD / Flux | Apply from Git; drift on a ConfigMap is shown like any other object |
| Spring Cloud Kubernetes, Go/PHP libraries | Read the API or mounted files directly (most apps should just read files) |
Fix / how to use it: one ConfigMap per concern and environment; env vars only for values that are fine to change by rollout; mounted files for anything the app can reload; versioned names (orders-config-v7, or Kustomize's hash suffix) plus immutable: true for large fleets. The chapter's manifests are in k8s/configmap.yaml.
Update propagation, the kubelet sync period and the subPath caveat Must-know
In plain words: Editing a ConfigMap or Secret changes the object in the API at once, but each node's kubelet copies the change into mounted volumes on its own schedule, and nothing ever changes a running process's environment.
Common misunderstanding: "The update is instant, or it never happens." Neither: mounted files are "eventually updated", with a delay that "can be as long as the kubelet sync period + cache propagation delay"; env vars and subPath mounts are never updated.
Definition: "The kubelet checks whether the mounted ConfigMap is fresh on every periodic sync." The period is the kubelet's syncFrequency ("syncFrequency is the max period between synchronizing running containers and config", default 1m in the KubeletConfiguration reference). The cache in front of the API is chosen by configMapAndSecretChangeDetectionStrategy: Watch (the default), Cache (TTL) or Get (straight to the API server), so the extra delay is the watch propagation delay, the TTL, or zero. Secrets mounted as volumes follow the same rules ("Kubernetes tracks this and updates the data in the volume, using an eventually-consistent approach"). Two exceptions: "ConfigMaps consumed as environment variables are not updated automatically and require a pod restart", and "A container using a ConfigMap as a subPath volume mount will not receive ConfigMap updates." (the Secret page says the same for Secrets).
Why subPath is frozen: a full-directory mount shows the kubelet's directory, inside which the files are symlinks the kubelet can repoint (see the atomic writer); a subPath mount bind-mounts one resolved file into the container, so the container keeps the old inode when the kubelet repoints the symlink.
T0 kubectl apply: orders-config log_level info -> debug (API object updated immediately)
T0+w kubelet's watch-based cache on node-b receives the new object (w = watch delay, usually small)
T0+<=1m next periodic sync for the Pod: kubelet sees the volume is stale, writes a new
timestamped dir and swaps ..data atomically (sync period default 1m)
T0+<=1m config.Watcher in orders-api gets directory events, debounces, re-reads, swaps config
always env var LOG_LEVEL in the same Pod still says "info"; /etc/nginx/conf.d/tuning.conf
(subPath) still has the old content until the Pod is replacedReal scenarios:
- Feature flag flipped in a ConfigMap at 10:00; one replica picks it up at 10:00:20, another at 10:00:55: for under a minute, users see both behaviours. Plan flag semantics for that.
- An Nginx
default.confmounted with subPath "does not reload": it is not even updated on disk. Mount the directory instead, or roll the Deployment. - A cert-manager renewal updates a
kubernetes.io/tlsSecret; an app that reads the key file on every TLS handshake (or watches it) keeps working; one that loaded the key at start serves the expired certificate until restarted. - Someone raises
syncFrequencyto reduce kubelet work and config changes start taking minutes.
| Consumer | Sees an edit | How fast |
|---|---|---|
Env, envFrom, configMapKeyRef, secretKeyRef | No | Next Pod |
| ConfigMap / Secret volume (no subPath) | Yes | Sync period + cache delay (about a minute by default) |
| subPath of any ConfigMap / Secret volume | No | Next Pod |
| Projected volume with ConfigMap / Secret sources | Yes (those sources) | As volumes |
| Immutable ConfigMap / Secret | Cannot be edited | Rollout to a new name |
| Secrets Store CSI mount | Only with --enable-secret-rotation | --rotation-poll-interval (default 2m) |
Fix: decide per value: "restart to change" values go in env and are rolled out (Reloader or a checksum annotation); "live" values go in mounted files that the app watches; never subPath a file you expect to change.
Secrets: types, base64, size, data vs stringData Must-know
In plain words: A Secret is a ConfigMap-shaped object for credentials. Its values are base64 text, which anyone can decode; the protection comes from RBAC, encryption at rest and how the node handles it.
Common misunderstanding: "base64 hides the password." It is an encoding for binary safety. echo Y2hhbmdlLW1l | base64 -d prints change-me.
Definition: "Secrets are similar to ConfigMaps but are specifically intended to hold confidential data." The type field tells tooling what keys to expect; the built-in types are:
| Type | Required keys | Used for |
|---|---|---|
Opaque | any | Arbitrary data; the default ("an empty string is treated as an Opaque type") |
kubernetes.io/service-account-token | token, ca.crt, namespace (filled by the control plane) | Legacy long-lived ServiceAccount tokens; prefer projected tokens |
kubernetes.io/dockercfg | .dockercfg | Old registry config format |
kubernetes.io/dockerconfigjson | .dockerconfigjson | Registry credentials for imagePullSecrets |
kubernetes.io/basic-auth | username and/or password | Basic auth credentials |
kubernetes.io/ssh-auth | ssh-privatekey | SSH keys |
kubernetes.io/tls | tls.crt, tls.key (presence checked, contents not) | TLS server or client certificates (cert-manager writes these) |
bootstrap.kubernetes.io/token | token-id, token-secret, ... | Node bootstrap tokens in kube-system |
"The values for all keys in the data field have to be base64-encoded strings"; stringData accepts plain strings on write and is merged into data (it is write-only: a get shows only data). "Individual Secrets are limited to 1MiB in size." immutable: true works as for ConfigMaps. On the node: "A Secret is only sent to a node if a Pod on that node requires it", and for volumes "the kubelet stores a copy of the data into a tmpfs so that the confidential data is not written to durable storage."
kubectl apply -f k8s/secret.yaml (orders-db, stringData.password: change-me)
1 kube-apiserver converts stringData into data.password = Y2hhbmdlLW1l (base64)
2 encryption config? no -> stored as-is in etcd; yes -> first provider encrypts the bytes
3 Pod on node-b mounts orders-db: kubelet fetches it (RBAC as the node), writes files on tmpfs
4 container reads /etc/orders/secrets/database-url as plain text
5 Pod deleted -> kubelet deletes its local copyReal scenarios: a Secret YAML with data: committed to a public repository and decoded by a bot within minutes; an imagePullSecrets entry pointing to a Secret of type Opaque that the kubelet ignores; a TLS Secret created with the key and certificate swapped, which the API server accepts (it requires the tls.crt and tls.key keys, "although the API server doesn't actually validate the values for each key") and the Ingress controller then fails to load; a kubectl get secret -o yaml pasted into a support ticket.
| Platform | What it adds around Secrets |
|---|---|
| EKS | Envelope encryption of Secrets with an AWS KMS key; Secrets Store CSI AWS provider; ESO AWS providers |
| GKE | Application-layer Secrets encryption with Cloud KMS; Secret Manager add-on / CSI provider |
| AKS | KMS etcd encryption with Azure Key Vault; Key Vault provider for the Secrets Store CSI driver |
| OpenShift / Rancher | Encryption config managed by the platform; ESO and Vault integrations as operators |
| Vault, AWS/GCP/Azure secret managers | The real source of truth when ESO or the CSI driver is used |
Fix: treat a Secret's YAML as plain text; never commit it unencrypted; prefer stringData only in throwaway examples; use the typed Secret kinds so tooling validates them; combine with encryption at rest and RBAC.
Encryption at rest: EncryptionConfiguration and the KMS provider Important
In plain words: Without extra configuration, the API server writes Secrets to etcd as readable bytes, so an etcd backup or disk is a copy of every credential. An encryption config makes the API server encrypt them before writing.
Common misunderstanding: "My config file lists aescbc, so I am encrypted." Only the first provider encrypts, existing objects stay as they were until rewritten, and aescbc keys sit on the control-plane disk next to the data.
Definition: "By default, the API server stores plain-text representations of resources into etcd, with no at-rest encryption." kube-apiserver --encryption-provider-config=<file> points at an EncryptionConfiguration (apiserver.config.k8s.io/v1) listing, per resource, an ordered providers array. "The first provider in the list is used to encrypt resources written into the storage." On reads each provider is tried in order. If identity is first, "the default identity provider does not provide any confidentiality protection." Providers, as the docs rate them:
| Provider | Scheme | Docs' verdict |
|---|---|---|
identity | none | The default; plain text |
aescbc | AES-CBC with PKCS#7 padding | "Weak"; "Not recommended due to CBC's vulnerability to padding oracle attacks"; key on the control-plane host |
aesgcm | AES-GCM with random nonce | "Must be rotated every 200,000 writes"; only with automated key rotation |
secretbox | XSalsa20 and Poly1305 | "Strong"; key on the control-plane host |
kms v1 | Envelope, DEK per resource | Deprecated since v1.28; slow |
kms v2 | Envelope, DEK per API server from a seed, KEK in the external KMS | "Strongest", "Fast", "Available as stable from Kubernetes v1.29" |
With KMS, "The KMS provider uses gRPC to communicate with a specific KMS plugin over a UNIX domain socket"; the plugin runs on the control-plane hosts and talks to AWS KMS, Cloud KMS, Azure Key Vault, Vault Transit or an HSM. After changing the file, restart every API server and rewrite all Secrets so they are stored with the new provider: kubectl get secrets --all-namespaces -o json | kubectl replace -f -.
Turning on KMS v2 on a self-managed cluster
1 deploy the KMS plugin on every control-plane node (socket /var/run/kmsplugin/socket.sock)
2 write enc.yaml: secrets -> [kms v2, identity] (identity last: old plain data still readable)
3 add --encryption-provider-config to kube-apiserver, restart each API server
4 kubectl get secrets -A -o json | kubectl replace -f - (every Secret rewritten -> encrypted)
5 verify with etcdctl get /registry/secrets/shop/orders-db: value starts with k8s:enc:kms:v2:
6 remove identity from the list, restart againReal scenarios: an etcd snapshot stored in an S3 bucket with broad read access; a compliance audit asking "are Secrets encrypted at rest with a customer-managed key?"; a cluster where aescbc was enabled years ago and nobody can rotate the key; a managed cluster where the team assumed the cloud's disk encryption covered the same threat (it covers stolen disks, not etcd API reads or backups).
| Platform | How you enable it |
|---|---|
| kubeadm / self-managed | Write the file, add the flag to the static Pod manifest, restart API servers, rewrite Secrets |
| EKS | Secrets envelope encryption with a KMS key (default on newer clusters; customer-managed key optional) |
| GKE | Application-layer secrets encryption with a Cloud KMS key |
| AKS | KMS etcd encryption with an Azure Key Vault key |
| k3s | --secrets-encryption server flag ("K3s supports enabling secrets encryption at rest"); --secrets-encryption-provider (default aescbc) |
Fix: KMS v2 first, a fallback provider only during migration, rewrite all Secrets, then remove the fallback; keep the KMS key's access policy as tight as etcd's. The file is k8s/encryption-config.yaml.
RBAC for secrets: get, list, watch and the Pod-creation loophole Must-know
In plain words: Being allowed to read one Secret by name is narrow; being allowed to list Secrets is being allowed to read all of them; being allowed to create Pods is being allowed to read all of them through a mount.
Common misunderstanding: "A read-only role with get/list/watch on everything is harmless." For Secrets, list is read: "granting list or watch permissions on Secrets allows a subject to read all Secret data in that namespace, not only the Secrets explicitly referenced by its Pods."
Definition: RBAC rules grant verbs on resources; resourceNames narrows a rule to named objects ("When specified, requests can be restricted to individual instances of a resource"), but it cannot restrict create or deletecollection, and a list/watch restricted by name requires a metadata.name field selector. The good-practices page adds: "list and watch access also effectively allow for users to reveal the Secret contents", and permission to create workloads "implicitly grants access to many other resources in that namespace, such as Secrets, ConfigMaps, and PersistentVolumes that can be mounted in Pods." The Secret page names the escalation: "anyone who is authorized to create a Pod in a namespace can use that access to read any Secret in that namespace; this includes indirect access such as the ability to create a Deployment." And on the node: "Any containers that run with privileged: true on a node can access all Secrets used on that node." The built-in view ClusterRole deliberately excludes Secrets.
Developer with "edit" on namespace shop but no "get secrets"
1 kubectl get secret orders-db -> Forbidden
2 kubectl run peek --image=busybox --overrides='{... volumes: secret orders-db ...}' -- cat /s/password
3 the Pod mounts orders-db (the kubelet reads it as the node, not as the developer)
4 kubectl logs peek -> change-me
-> namespace = trust boundary for Secrets; separate namespaces for separate teams| Grant | What it really allows |
|---|---|
get on secrets with resourceNames: [orders-db] | Read one named Secret (what a rotation Job or controller needs; an app that only mounts Secrets needs nothing) |
get on secrets (no names) | Read any Secret whose name you know or guess |
list / watch on secrets | Read all Secret data in the namespace (list responses include data) |
create on pods, deployments, jobs, ... | Read any Secret in the namespace by mounting it; run as any ServiceAccount there |
create on pods/exec | Read whatever a running container can read (its mounted Secrets, its env) |
privileged: true on a node | All Secrets of all Pods on that node |
Fix: apps get no RBAC on Secrets at all (the kubelet mounts them, so orders-api has no Role); controllers and jobs that call the API get get/update by name (the orders-db-rotator Role); humans get Secrets access only in break-glass roles; separate namespaces per trust level; Pod Security Admission to stop privileged Pods. The Role is k8s/rbac-secrets.yaml; RBAC in depth is Kubernetes Security.
Environment variables vs files for secrets Must-know
In plain words: A secret in an environment variable is copied into the process at start and goes wherever the environment goes. A secret in a mounted file stays on a RAM disk and can be rotated under a running process.
Common misunderstanding: "Env vars are the twelve-factor way, so they are the secure way." Twelve-factor is about separating config from code, not about secrecy; env vars leak through child processes, crash reporters, /proc/<pid>/environ, debug endpoints and kubectl describe of the Pod spec when someone used value: instead of valueFrom:.
Definition: env[].valueFrom.secretKeyRef (one key) and envFrom[].secretRef (all keys) inject at container creation; "When a volume contains data from a Secret, and that Secret is updated, Kubernetes tracks this and updates the data in the volume". Files are on tmpfs, can be limited to the keys a container needs (items), have a mode (defaultMode, e.g. 0400), and are per-container (only containers with a volumeMount see them). The good-practices page recommends limiting Secret access to the containers that need it.
| Aspect | Environment variable (secretKeyRef, envFrom) | Mounted secret file |
|---|---|---|
| Rotation | Needs a new Pod | Updated in place (kubelet sync period) |
| Who can read | The process, its children, anything that dumps env | Processes with file permission in that container |
| Accidental leaks | Logs of env, error pages, APM "environment" tabs | Much rarer (must read the file explicitly) |
| App support | Universal | App must read a path (*_FILE convention) |
| Size / format | One line, no binary | Any bytes (keys, certs, keystores) |
| Missing Secret | Container fails with CreateContainerConfigError | Pod stuck in ContainerCreating with a mount error |
Database password rotation, two designs
env : ESO updates Secret orders-db -> nothing happens -> Reloader rolls the Deployment ->
new Pods read the new password -> old Pods drain (needs the DB to accept both for a while)
file : ESO updates Secret orders-db -> kubelet swaps the file within about a minute ->
config.SecretFile TTL expires -> next connection uses the new password, no restartFix: credentials as files with a *_FILE variable pointing at them (the Go LoadStatic and Laravel database.php snippets both support it); env vars only for non-secret settings or for apps you cannot change.
External Secrets Operator: SecretStore and ExternalSecret Important
In plain words: ESO is a controller that logs in to your real secret manager, reads entries, and writes them into ordinary Kubernetes Secrets, again and again on a schedule.
Common misunderstanding: "With ESO there are no Kubernetes Secrets any more." There are: ESO's output is a Secret, so encryption at rest and RBAC still matter. What changes is the source of truth and rotation.
Definition: "The controller fetches secrets from an external API and creates Kubernetes secrets. If the secret from the external API changes, the controller will reconcile the state in the cluster and update the secrets accordingly." The model separates concerns: "The ExternalSecret specifies what to fetch, the SecretStore specifies how to access." A SecretStore is namespaced ("By design, SecretStores are bound to a namespace and can not reference resources across namespaces"); a ClusterSecretStore can be referenced from any namespace. The API group is external-secrets.io/v1. Important ExternalSecret fields: refreshPolicy (Periodic default, OnChange, CreatedOnce), refreshInterval ("May be set to zero to fetch and create it once"), target.creationPolicy (Owner default: "If the ExternalSecret is deleted, the Secret will also be deleted"; Orphan; Merge), target.deletionPolicy (Retain default, Delete, Merge), target.template (Go templates to build files or connection strings), data[] and dataFrom[] (extract a whole JSON object). Providers include AWS Secrets Manager and Parameter Store, HashiCorp Vault, Google Secret Manager, Azure Key Vault, IBM, Akeyless, CyberArk and more. Vault auth with Kubernetes: Vault "validates the service account token by using the TokenReview API", and "In Vault 1.21 and later, roles must include an audience or authentication will fail."
ExternalSecret orders-db (refreshInterval 15m) against SecretStore vault
1 ESO reads SecretStore vault: server, KV v2 mount "secret", auth kubernetes role orders-api
2 ESO requests a token for ServiceAccount orders-api (audience vault), logs in to Vault
3 reads secret/data/shop/orders-db -> {username, password}
4 renders target.template -> writes Secret orders-db (ownerReference -> the ExternalSecret)
5 status.conditions Ready=True, refreshTime set; every 15 m: repeat 2-4, update only on change
6 someone rotates the password in Vault -> within 15 m the Secret changes -> files followReal scenarios: one Vault for twenty clusters, each with its own Kubernetes auth mount; AWS Secrets Manager rotation Lambdas changing RDS passwords monthly while ESO keeps the cluster in sync; a ClusterSecretStore that every namespace could reference, letting team A read team B's secrets (fix with namespace selectors / conditions on the store); PushSecret sending a cert-manager certificate to a cloud secret manager.
| Provider (ESO) | Auth from the cluster without static keys |
|---|---|
| AWS Secrets Manager / Parameter Store | EKS Pod Identity on the ESO controller (no auth section; ESO docs: serviceAccountRef cannot be combined with Pod Identity) or IRSA (auth.jwt.serviceAccountRef) |
| HashiCorp Vault / OpenBao | Kubernetes auth (TokenReview), JWT/OIDC, AppRole |
| Google Secret Manager | GKE Workload Identity |
| Azure Key Vault | Azure Workload Identity |
| Doppler, 1Password, Bitwarden, Infisical, ... | Provider tokens (themselves a bootstrap Secret) |
Fix: one SecretStore per namespace (or a guarded ClusterSecretStore), short refresh for rotating credentials, creationPolicy: Owner so cleanup follows Git, and files rather than env vars in the consumer. Manifests: k8s/external-secrets.yaml.
Secrets Store CSI Driver: secrets as tmpfs files, no Secret object Important
In plain words: Instead of copying secrets into Kubernetes, a CSI driver on every node fetches them when a Pod starts and mounts them straight into that Pod as files.
Common misunderstanding: "The CSI driver rotates secrets automatically." Rotation is an alpha feature: "NOTE: This alpha feature is not enabled by default." And env vars still need a Secret object plus a restart: "The pod needs to be restarted to get the latest secret as environment variable."
Definition: The Secrets Store CSI Driver "Integrates secrets stores with Kubernetes via a Container Storage Interface (CSI) volume" and is a SIG Auth subproject. A SecretProviderClass (secrets-store.csi.x-k8s.io/v1) names a provider and its parameters; the Pod mounts a csi volume with driver: secrets-store.csi.k8s.io and volumeAttributes.secretProviderClass. On Pod start the driver "communicates with the provider using gRPC to retrieve the secret content" and mounts it as tmpfs. Supported providers listed in the concepts page: Akeyless, AWS, Azure, Conjur, GCP, OpenBao and Vault. Optional secretObjects mirror the content into a Kubernetes Secret, but "The volume mount is required for the Sync With Kubernetes Secrets". Security trade-off stated by the project: "The Secrets Store CSI Driver daemonset runs as root in a privileged pod", and providers also run as root to create a Unix socket under hostPath. With rotation on (--enable-secret-rotation=true), the driver uses CSI RequiresRepublish and --rotation-poll-interval (default 2m).
Pod orders-api-csi-demo starts on node-b
1 kubelet sees volume csi driver=secrets-store.csi.k8s.io -> NodePublishVolume to the driver socket
2 driver reads SecretProviderClass orders-vault, forwards the Pod's ServiceAccount token to the vault provider
3 provider logs in to Vault as role orders-api, reads database/creds/orders (dynamic credentials)
4 driver creates a tmpfs, writes db-username and db-password, bind-mounts it at /mnt/secrets
5 secretObjects set -> controller creates Secret orders-db-csi (exists while a Pod mounts the volume)
6 Pod deleted -> volume torn down, tmpfs gone| ESO | Secrets Store CSI Driver | |
|---|---|---|
| Kubernetes Secret created | Always | Only with secretObjects (and only while mounted) |
| When fetched | Continuously, refreshInterval | At Pod start (+ alpha rotation) |
| Env var support | Yes (secretKeyRef) | Only through the synced Secret |
| Runs as | One controller Deployment | Privileged DaemonSet + provider DaemonSet on every node |
| Per-Pod identity to the store | No (the store's identity) | Yes (the Pod's ServiceAccount token is forwarded) |
| Works when the store is down | Yes, the Secret already exists | New Pods fail to start |
Fix: use the CSI driver when the requirement is "no secret material in etcd" or per-Pod identity to the store; otherwise ESO is simpler to operate. Manifests: k8s/secretproviderclass.yaml.
GitOps secrets: Sealed Secrets and SOPS Important
In plain words: GitOps wants every manifest in Git, but a Secret in Git is a leak. Both tools commit ciphertext and decrypt it only inside the cluster (Sealed Secrets) or in the GitOps tool (SOPS).
Common misunderstanding: "Rotating the Sealed Secrets key protects secrets that leaked." The project's FAQ answers exactly this: sealing keys are "not access control keys", and "If a secret is leaked there is no going back"; you rotate the secret (the database password), not just the sealing key.
Definition, Sealed Secrets: a controller plus the kubeseal CLI; "The kubeseal utility uses asymmetric crypto to encrypt secrets that only the controller can decrypt." The result is a SealedSecret (bitnami.com/v1alpha1) that the controller turns into a normal Secret. Scopes: "strict (default): the secret must be sealed with exactly the same name and namespace", namespace-wide, cluster-wide. "Since v0.9.x certificates get automatically renewed every 30 days"; old keys are kept so old SealedSecrets still decrypt. Back up the controller's private keys: without them, re-seal everything.
Definition, SOPS: "SOPS is an editor of encrypted files that supports YAML, JSON, ENV, INI and BINARY formats and encrypts with AWS KMS, GCP KMS, Azure Key Vault, HuaweiCloud KMS, age, and PGP." "By default, SOPS encrypts all the values of a YAML, JSON, ENV, or INI file and leaves the keys in cleartext", and --encrypted-regex '^(data|stringData)$' "will encrypt the values under the data and stringData keys in a YAML file containing kubernetes secrets." A .sops.yaml file with creation_rules and path_regex chooses keys per path; "The first regex that matches is selected". A data key is encrypted for each master key, so "As long as one of the KMS or PGP method is still usable, you will be able to access your data." Flux decrypts SOPS natively; Argo CD needs a plugin such as KSOPS or helm-secrets.
Committing a new database password with SOPS (Flux)
1 edit clusters/prod/orders-db.secret.yaml locally with: sops edit clusters/prod/orders-db.secret.yaml
2 sops decrypts with your KMS/age identity, opens the editor, re-encrypts values on save
3 git diff shows metadata in clear and ENC[AES256_GCM,...] for data -> review is still possible
4 Flux kustomize-controller (decryption: provider sops) decrypts in-cluster with its own key
5 applies the plain Secret to the API server -> encryption at rest takes over from here| Sealed Secrets | SOPS | ESO (for comparison) | |
|---|---|---|---|
| Ciphertext lives in | Git (SealedSecret) | Git (encrypted values) | Nowhere; the store holds plain values |
| Who decrypts | In-cluster controller | Flux / Argo CD plugin / CI | ESO reads plain values over TLS |
| Key material | Controller key pair in the cluster | KMS key / age / PGP outside the cluster | Store credentials |
| Diff readability | Opaque blob per value | Keys visible, values encrypted | No secret in Git at all |
| Multi-cluster | Seal per cluster key (or share keys) | One KMS key for many clusters | One store for many clusters |
| Rotation | Re-seal and commit | sops edit / sops rotate and commit | Change it in the store |
Fix: small teams on one cluster: Sealed Secrets; Flux shops with cloud KMS: SOPS; organisations that already run Vault or a cloud secret manager: ESO, and keep Git free of secrets. Files: k8s/gitops-secrets.yaml and k8s/sops.yaml.
Config reload: checksum annotation, Reloader, hot reload Must-know
In plain words: There are only two ways for a running app to get new config: be replaced by a new Pod, or read the new files itself. Everything else is a way to trigger one of those two.
Common misunderstanding: "kubectl rollout restart after every config change is fine." It works, but it is manual, invisible in Git, and forgotten exactly when it matters; and it is useless for apps that could reload in place.
Definition: three patterns.
- Checksum annotation (render-time). Helm's tips page: "The sha256sum function can be used to ensure a deployment's annotation section is updated if another file changes". A hash of the ConfigMap template goes into
spec.template.metadata.annotations, so a config change is a Pod-template change and the Deployment rolls. Kustomize'sconfigMapGeneratorhash suffix achieves the same by renaming the ConfigMap. Neither sees a Secret changed by ESO at runtime. - Reloader (runtime controller). "Reloader is a Kubernetes controller that automatically triggers rollouts of workloads (like Deployments, StatefulSets, and more) whenever referenced Secrets, ConfigMaps or optionally CSI-mounted secrets are updated." Opt-in with
reloader.stakater.com/auto: "true"(rolls on any referenced ConfigMap or Secret, including file-mounted ones the app hot-reloads) or the named formconfigmap.reloader.stakater.com/reload: "orders-env"(rolls only on those; the orders-api Deployment uses it so file-mounted config stays a hot reload). Default strategyenv-varsadds a dummy env var to the Pod template;annotationsaddsreloader.stakater.com/last-reloaded-fromand is "Ideal for GitOps tools like ArgoCD, as it avoids triggering unwanted sync diffs." - Hot reload (in the app). The app watches the mounted directory and swaps its config atomically; no Pod is replaced. Watch the directory, not the file: fsnotify warns that "Watching individual files (rather than directories) is generally not recommended as many programs (especially editors) update files atomically", and the kubelet is such a program.
Helm upgrade changes values.yaml log level, with and without the checksum annotation
without: ConfigMap updated -> Deployment spec unchanged -> no rollout -> env-based apps keep "info"
with : checksum/config changes -> new ReplicaSet -> Pods replaced one by one -> all on "debug"
runtime: ESO rotates Secret orders-db -> Helm never ran -> only Reloader (or hot reload) reacts| Pattern | Reacts to | Restarts Pods | Works with env vars | Needs code changes |
|---|---|---|---|---|
| Checksum annotation (Helm) / hash suffix (Kustomize) | Changes in Git rendered by the tool | Yes, rolling | Yes | No |
| Reloader | Any change to a referenced ConfigMap/Secret in the cluster | Yes, rolling | Yes | No |
kubectl rollout restart | A human | Yes, rolling | Yes | No |
| Hot reload (fsnotify / polling) | Mounted file changes | No | No | Yes |
| App polls an API (Consul, etcd, Unleash, LaunchDarkly) | Store changes | No | No | Yes |
Fix: hot reload for flags and log levels (the Go watcher), Reloader or checksum for everything else, and make every reload validate before it applies.
Pod volumes: emptyDir, hostPath, projected, downwardAPI Must-know
In plain words: A Pod volume is a directory the kubelet prepares before the containers start. Some are scratch space that dies with the Pod, some are windows into the node, some are generated files.
Common misunderstanding: "emptyDir is like /tmp, it does not count." It is allocated from node ephemeral storage (or RAM with medium: Memory, where "files you write count against the memory limit of the container that wrote them"); filling it can get the Pod evicted.
Definition: "At its core, a volume is a directory, possibly with some data in it, which is accessible to the containers in a pod." Declared once in .spec.volumes, mounted per container in volumeMounts. "For any kind of volume in a given Pod, data is preserved across container restarts."
emptyDir: created when the Pod is assigned to a node, shared by all its containers; "When a Pod is removed from a node for any reason, the data in the emptyDir is deleted permanently", but "A container crashing does not remove a Pod from a node."sizeLimitcaps it; without a limit, memory-backed volumes "are sized to node allocatable memory".hostPath: a file or directory of the node. "Using the hostPath volume type presents many security risks. If you can avoid using a hostPath volume, you should." Reasons given: it "can expose privileged system credentials (such as for the kubelet) or privileged APIs (such as the container runtime socket) that can be used for container escape", identical Pods behave differently on different nodes, and "hostPath volume usage is not treated as ephemeral storage usage". Legitimate users: log shippers reading/var/log, CSI node plugins, node agents.type: DirectoryOrCreateand friends check what is at the path.projected: "combines several sources, such as a Secret and a ConfigMap, into one directory." Sources:secret,downwardAPI,configMap,serviceAccountToken,clusterTrustBundle,podCertificate. A projectedserviceAccountTokenis short-lived and audience-bound:expirationSeconds"defaults to 1 hour and must be at least 10 minutes (600 seconds)", and the kubelet refreshes it.downwardAPI: Pod facts as env vars (fieldRef: metadata.name,status.podIP,spec.nodeName;resourceFieldRef: limits.memory) or files (metadata.labels,metadata.annotations). After an in-place resize "a downward API volume will be updated, but environment variables will not be updated unless the container restarts."
Pod with emptyDir medium: Memory, sizeLimit 256Mi, container memory limit 512Mi
1 app writes 300 MiB of temp files to /cache (tmpfs)
2 those pages are charged to the container's memory cgroup
3 app heap 250 MiB + tmpfs 300 MiB > 512 MiB -> OOMKilled, though "memory use" in the app looks fine
4 or: emptyDir usage > sizeLimit -> kubelet evicts the Pod
-> use disk-backed emptyDir for big scratch, Memory only for small hot files| Volume | Typical legitimate use | Abuse to avoid |
|---|---|---|
emptyDir | Laravel storage/framework, sidecar hand-off, sort spill files | Storing anything users uploaded |
emptyDir medium: Memory | Small secrets or sockets that must not touch disk | Large caches without a memory budget |
hostPath | Node agents, CSI node plugins, log collectors (read-only) | App data, the container runtime socket in app Pods |
projected | Token + CA + config in one directory | - |
downwardAPI | POD_NAME for logs, memory limit for runtime tuning (GOMEMLIMIT) | Building identity on labels anyone can edit |
generic ephemeral | Per-Pod scratch disk from a StorageClass (large, fast) | Data you expect after the Pod is gone |
Fix: set sizeLimit and ephemeral-storage requests/limits; forbid hostPath with Pod Security Admission (baseline already disallows it) except for node-level namespaces; use projected service-account tokens with an explicit audience for anything that talks to Vault or a cloud.
PersistentVolumes and PersistentVolumeClaims: binding and phases Must-know
In plain words: The application writes a claim ("I need this much storage of this kind"); the cluster finds or creates a volume and ties the two together, one to one, until the claim is deleted.
Common misunderstanding: "The PVC is the disk." The PVC is a namespaced request; the PV is the cluster-scoped record of the real disk; the disk itself lives in the cloud or the storage array. Deleting the Pod deletes neither.
Definition: "A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Classes." It has "a lifecycle independent of any individual Pod that uses the PV." "A PersistentVolumeClaim (PVC) is a request for storage by a user. It is similar to a Pod. Pods consume node resources and PVCs consume PV resources." Binding: "A control loop in the control plane watches for new PVCs, finds a matching PV (if possible), and binds them together", and "A PVC to PV binding is a one-to-one mapping, using a ClaimRef". "Claims will remain unbound indefinitely if a matching volume does not exist." The user "will always get at least what they asked for, but the volume may be in excess of what was requested." Storage Object in Use Protection keeps a PVC used by a Pod from being removed until the Pod is gone (finalizer kubernetes.io/pvc-protection). PV phases: Available, Bound, Released, Failed; PVC phases: Pending, Bound, Lost.
Static provisioning (an admin created PV nfs-reports-100Gi, class "", RWX)
1 user applies PVC reports (no class, 50Gi, RWX) -> Pending
2 PV controller finds nfs-reports-100Gi: class matches (""), modes match, 100Gi >= 50Gi
3 binds: PV.spec.claimRef = shop/reports, PVC.spec.volumeName = nfs-reports-100Gi -> both Bound
4 PVC shows capacity 100Gi (got more than asked)
5 user deletes the PVC -> PV Released (reclaimPolicy Retain), not reusable until an admin clears claimRefReal scenarios: a PVC stuck Pending for hours because its storageClassName has a typo; a "deleted" volume still billed because the PV was Retain and nobody cleaned up; an admin removing claimRef on a Released PV and a new claim inheriting the previous tenant's data; a namespace deleted with all its PVCs and, through Delete, all its disks.
| Platform | Default StorageClass and driver |
|---|---|
| EKS | gp2 in-tree name historically; install the EBS CSI driver (ebs.csi.aws.com) and a gp3 class; EKS Auto Mode uses ebs.csi.eks.amazonaws.com |
| GKE | standard-rwo / premium-rwo (Compute Engine PD CSI driver); Filestore CSI for RWX |
| AKS | CSI drivers by default since Kubernetes 1.21: Azure Disk (disk.csi.azure.com), Azure Files (file.csi.azure.com) for RWX |
| kind / minikube / k3s | standard / local-path style provisioners writing to a node directory |
| On-prem | Rook-Ceph (RBD, CephFS), Longhorn, OpenEBS, Portworx, vendor array CSI drivers |
Fix: let a StorageClass provision; use static PVs only for pre-existing data (and then pre-bind with claimRef or volumeName); watch kubectl get pv for Released volumes; treat namespace deletion as data deletion.
StorageClass, the provisioner, dynamic provisioning and WaitForFirstConsumer Must-know
In plain words: A StorageClass is a recipe for disks: which driver creates them, with what options, whether they can grow, what happens on delete, and when to create them.
Common misunderstanding: "Binding mode is a detail." With the default Immediate mode, a zonal disk is created before the scheduler knows where the Pod will run; the Pod may then be unschedulable because no node in that zone fits.
Definition: A StorageClass has provisioner (the CSI driver name, e.g. ebs.csi.aws.com), parameters (driver-specific: EBS type, iops, throughput, encrypted, kmsKeyId, csi.storage.k8s.io/fstype), reclaimPolicy ("If no reclaimPolicy is specified when a StorageClass object is created, it will default to Delete"), allowVolumeExpansion, mountOptions, volumeBindingMode and allowedTopologies. "When a PVC does not specify a storageClassName, the default StorageClass is used" (the one annotated storageclass.kubernetes.io/is-default-class: "true"). Binding mode: "When unset, Immediate mode is used by default"; for topology-constrained backends "PersistentVolumes will be bound or provisioned without knowledge of the Pod's scheduling requirements. This may result in unschedulable Pods." WaitForFirstConsumer "will delay the binding and provisioning of a PersistentVolume until a Pod using the PersistentVolumeClaim is created", so the volume is created in the topology (zone, node) the scheduler picked. Do not combine it with nodeName: "the scheduler will be bypassed and PVC will remain in pending state."
StatefulSet cache with 3 replicas, class gp3 (WaitForFirstConsumer), zones a/b/c, topology spread
1 PVCs data-cache-0..2 created -> Pending (WaitForFirstConsumer), no disks yet
2 scheduler places cache-0 in zone a, cache-1 in b, cache-2 in c (spread constraint)
3 scheduler annotates each PVC with the selected node -> external-provisioner calls CreateVolume
with accessibility requirements = that zone
4 three EBS volumes appear, one per zone; PVs carry node affinity for their zone
5 cache-1 later rescheduled: it can only go to a zone-b node (its PV's node affinity)Real scenarios: a PostgreSQL Pod Pending because "node(s) didn't match PersistentVolume's node affinity" (the scheduler's ErrReasonNodeConflict) when the disk was made in zone a and zone a is out of capacity; two StorageClasses both marked default after an upgrade (Kubernetes "uses the most recently created default StorageClass"); a cost spike from io2 used where gp3 sufficed; an on-prem cluster with no provisioner, where every PVC waits for an admin.
| Driver | provisioner | RWX? | Expansion | Snapshots |
|---|---|---|---|---|
| AWS EBS | ebs.csi.aws.com | Only Block multi-attach on io1/io2, with application fencing | Yes | Yes |
| AWS EFS | efs.csi.aws.com | Yes (NFS) | Elastic | No (backup via AWS Backup) |
| GCE PD / Hyperdisk | pd.csi.storage.gke.io | ROX; RWX only for Hyperdisk Balanced HA in Block mode | Yes | Yes |
| Filestore | filestore.csi.storage.gke.io | Yes (NFS) | Yes | Yes (Filestore backups) |
| Azure Disk / Files | disk.csi.azure.com / file.csi.azure.com | Files: yes | Yes | Yes |
| Rook-Ceph RBD / CephFS | rook-ceph.rbd.csi.ceph.com / ...cephfs.csi.ceph.com | CephFS: yes | Yes | Yes |
| Local static | kubernetes.io/no-provisioner | No | No | No |
Fix: every StorageClass for zonal block storage uses WaitForFirstConsumer; exactly one default class; a separate Retain class for databases; allowVolumeExpansion: true unless the driver cannot. File: k8s/storageclass.yaml.
Access modes: ReadWriteOnce, ReadOnlyMany, ReadWriteMany, ReadWriteOncePod Must-know
In plain words: The access mode says how many nodes (or Pods) may mount the volume at once, and whether they may write. It must be something the storage can actually do.
Common misunderstanding: "RWO protects my data from two writers." Two Pods on the same node can both mount an RWO volume read-write; and "Volume access modes do not enforce write protection once the storage has been mounted."
Definition: ReadWriteOnce: "the volume can be mounted as read-write by a single node. ReadWriteOnce access mode still can allow multiple pods to access (read from or write to) that volume when the pods are running on the same node." ReadOnlyMany: "the volume can be mounted as read-only by many nodes." ReadWriteMany: "the volume can be mounted as read-write by many nodes." ReadWriteOncePod (stable v1.29): "Use ReadWriteOncePod access mode if you want to ensure that only one pod across the whole cluster can read that PVC or write to it"; it is supported only for CSI volumes. "A volume can only be mounted using one access mode at a time, even if it supports many." Block disks (EBS, PD, Azure Disk) are RWO; shared file systems (EFS, Filestore, Azure Files, CephFS, NFS) give RWX. EBS multi-attach exists for io1/io2 in Block mode, but "Application-level coordination (e.g., via I/O fencing) is required to use multi-attach safely."
Deployment, replicas 1, RWO PVC, default RollingUpdate (maxSurge 25% -> 1 new Pod first)
1 new ReplicaSet creates Pod v2; scheduler puts it on node-c (old Pod v1 runs on node-a)
2 attach to node-c fails: a multi-attach error event, the volume is still attached to node-a
3 v2 stays ContainerCreating; v1 is not removed until v2 is Ready -> rollout deadlocked
fix: strategy Recreate (or a StatefulSet), or RWOP + Recreate if exactly one Pod may ever use itGKE's documentation describes exactly this: "Even Deployments with one replica using ReadWriteOnce volume are not recommended. This is because the default Deployment strategy creates a second Pod before bringing down the first Pod on a recreate."
| Need | Access mode | Storage that provides it |
|---|---|---|
| One database instance, one disk | RWO (or RWOP) | EBS, PD, Azure Disk, local PV, Ceph RBD |
| Guarantee a single writer Pod cluster-wide | RWOP | Any CSI driver with the RWOP-capable sidecars |
| Many Pods read a static dataset | ROX | PD multi-reader, NFS, a populated snapshot clone |
| Many Pods on many nodes write shared files | RWX | EFS, Filestore, Azure Files, CephFS, NFS (or better: object storage) |
Fix: Deployments with an RWO PVC use strategy: Recreate; per-replica data uses a StatefulSet; shared uploads go to object storage, not RWX (see Laravel).
Reclaim policy: Retain, Delete, Recycle Important
In plain words: The reclaim policy decides what happens to the real disk when its claim is deleted.
Common misunderstanding: "Deleting a PVC by mistake is recoverable." With Delete (the default for dynamically provisioned volumes), "deletion removes both the PersistentVolume object from Kubernetes, as well as the associated storage asset in the external infrastructure."
Definition: Retain: "When the PersistentVolumeClaim is deleted, the PersistentVolume still exists" and the volume is considered released, "But it is not yet available for another claim because the previous claimant's data remains on the volume"; an admin deletes the PV, cleans and deletes or reuses the asset. Delete: removes the PV and the disk; dynamically provisioned volumes "inherit the reclaim policy of their StorageClass, which defaults to Delete". Recycle: deprecated basic scrub, "only nfs and hostPath volume types support recycling". The policy of an existing PV can be patched (persistentVolumeReclaimPolicy). Since HonorPVReclaimPolicy (stable v1.33), finalizers make sure a Delete PV's disk is deleted even if the PV object is deleted before the PVC.
kubectl delete namespace shop (contains PVC data-cache-0 on class gp3 = Delete, orders-db PVCs on gp3-retain)
1 namespace controller deletes the PVCs
2 data-cache-0 -> PV reclaim Delete -> external-provisioner calls DeleteVolume -> EBS volume gone
3 orders-db-1 -> PV reclaim Retain -> PV Released, EBS volume kept, still billed
4 recovery: create PV manifest pointing at the volume handle, pre-bind to a new PVCReal scenarios: a team deletes and re-creates a Helm release to "reset" it and the chart's PVCs (class with Delete) take the database disks with them; a cluster migration where every PV was Retain, so the old account keeps hundreds of orphaned volumes; an admin patches persistentVolumeReclaimPolicy to Retain on a live PV before a risky namespace change; a statically provisioned NFS PV that sits Released and blocks new claims until someone clears claimRef.
| Where the policy comes from | Default | Note |
|---|---|---|
| Dynamically provisioned PV | The StorageClass reclaimPolicy | Defaults to Delete if the class omits it |
| Statically created PV | persistentVolumeReclaimPolicy in the PV | Set it explicitly; Retain is the safe choice |
| Existing PV | kubectl patch pv <name> -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}' | Changes only that PV, not the class |
| CloudNativePG / other operators | The StorageClass of their PVCs | Use a Retain class for database tiers |
| VolumeSnapshotContent | deletionPolicy of the VolumeSnapshotClass | Same idea for snapshots |
Fix: Retain classes for anything you cannot re-create; snapshots and backups for the rest; a periodic report of Released PVs so retained disks do not pile up.
Volume expansion Important
In plain words: To grow a volume, edit the PVC's requested size; the driver grows the disk and then the file system. Shrinking is not a thing.
Common misunderstanding: "I can edit the PV's capacity." "Directly editing the size of a PersistentVolume can prevent an automatic resize of that volume", because the control plane then concludes the resize already happened.
Definition: Stable since v1.24; "You can only expand a PVC if its storage class's allowVolumeExpansion field is set to true." "A new PersistentVolume is never created to satisfy the claim. Instead, an existing volume is resized." For CSI the external-resizer sidecar calls ControllerExpandVolume, then the kubelet calls NodeExpandVolume to grow the file system, online for in-use volumes on drivers that support it (stable v1.24). Conditions Resizing and FileSystemResizePending show progress. Cloud limits still apply (an EBS volume can be modified once every few hours).
kubectl patch pvc data-orders-db-1 -p '{"spec":{"resources":{"requests":{"storage":"100Gi"}}}}'
1 API validates: class allows expansion, new size > old
2 external-resizer -> ControllerExpandVolume -> EBS ModifyVolume to 100 GiB
3 PVC condition shows the file-system resize as pending (block device bigger, file system not yet)
4 kubelet on the node -> NodeExpandVolume -> resize2fs / xfs_growfs online
5 PVC status.capacity 100Gi; df inside the Pod shows the new sizeReal scenarios: a PostgreSQL volume fills at 3 a.m. and the class has allowVolumeExpansion: false, so the only path is a new, larger volume and a restore; someone edits the StatefulSet's volumeClaimTemplates size and nothing happens to the existing claims; an expansion stuck with the file-system resize pending because the driver only grows file systems offline and the Pod was never restarted; a PVC that cannot be shrunk back after a typo (1000Gi instead of 100Gi).
| Driver / platform | Expansion | Note |
|---|---|---|
| AWS EBS CSI | Online | Cloud-side modification limits apply between changes |
| GCE PD / Hyperdisk CSI | Online | Also VolumeAttributesClass for performance changes |
| Azure Disk CSI | Supported | Some disk types require detach first; check the driver docs |
| CSI drivers in general | If the driver implements ControllerExpandVolume / NodeExpandVolume | The VolumeExpansion plugin capability advertises it |
| CloudNativePG | Operator resizes its PVCs | resizeInUseVolumes (on by default; disable for drivers without online resize) |
Fix: alert at 80 % full, expand before the database stops; for StatefulSets, patch each PVC (the volumeClaimTemplates size only applies to new PVCs); operators like CloudNativePG resize their PVCs for you (resizeInUseVolumes).
Snapshots and clones: VolumeSnapshot, VolumeSnapshotClass, dataSource Important
In plain words: A VolumeSnapshot asks the storage system for a point-in-time copy of a PVC; restoring means creating a new PVC from it.
Common misunderstanding: "A volume snapshot is a database backup." It is a crash-consistent copy of blocks in the same storage system (often the same region and account). Without quiescing the database or using its own backup mechanism, it is like pulling the power cord, and it disappears with the account.
Definition: "A VolumeSnapshot is a request for snapshot of a volume by a user. It is similar to a PersistentVolumeClaim"; VolumeSnapshotContent is like a PV; VolumeSnapshotClass like a StorageClass (with driver and deletionPolicy). Stable since v1.20, but they "are CRDs, not part of the core API", "VolumeSnapshot support is only available for CSI drivers", and "The CRDs and snapshot controller installations are the responsibility of the Kubernetes distribution." The snapshot controller manages contents; the csi-snapshotter sidecar "triggers CreateSnapshot and DeleteSnapshot operations against a CSI endpoint". Restore: a PVC with dataSource: {kind: VolumeSnapshot, ...}. Clone: a PVC with dataSource: {kind: PersistentVolumeClaim, ...} (same namespace, same volumeMode, CSI dynamic provisioners only; "Destination volume can be the same or a different storage class as the source"). A restored or cloned PVC must request at least the source's size.
Before a risky migration on reports-data
1 kubectl apply VolumeSnapshot reports-data-2026-11-29 (class ebs-snapclass)
2 snapshot controller creates VolumeSnapshotContent; csi-snapshotter -> CreateSnapshot -> EBS snapshot
3 readyToUse: true
4 migration corrupts data -> create PVC reports-data-restored with dataSource = the snapshot
5 point the workload at the new PVC (or swap names), verify, delete the broken PVCFix: snapshots for fast, same-region rollback; real backups (database-native, copied to another region or account) for disaster recovery; deletionPolicy: Retain on the class if snapshots must outlive their Kubernetes objects. File: k8s/volumesnapshot.yaml. Backup theory: Backup, PITR & DR.
CSI architecture: controller plugin, node plugin, sidecars Important
In plain words: A CSI driver is two programs from the storage vendor: one central controller that creates and attaches disks through the vendor API, and one per node that mounts them. Kubernetes talks to both through small helper containers.
Common misunderstanding: "The kube-controller-manager calls the storage API." Not for CSI: "Kubernetes master components do not communicate directly (via a Unix Domain Socket or otherwise) with CSI drivers"; sidecars "watch the Kubernetes API and trigger the appropriate CSI operations against it."
Definition: The Container Storage Interface "is a standard for exposing arbitrary block and file storage systems to containerized workloads on Container Orchestration Systems (COs) like Kubernetes." A driver implements gRPC services: Identity, Node (NodeStageVolume, NodePublishVolume, ...), and optionally Controller (CreateVolume, ControllerPublishVolume, snapshots, expansion), advertised as capabilities (CREATE_DELETE_VOLUME, PUBLISH_UNPUBLISH_VOLUME, STAGE_UNSTAGE_VOLUME, VOLUME_ACCESSIBILITY_CONSTRAINTS for topology, ...). "A CSI driver is typically deployed in Kubernetes as two components: a controller component and a per-node component." The controller plugin "can be deployed as a Deployment or StatefulSet", with sidecars external-provisioner, external-attacher, external-snapshotter, external-resizer, using leader election. The node plugin is a DaemonSet with the driver and node-driver-registrar; "Kubelet directly issues CSI calls (like NodeStageVolume, NodePublishVolume, etc.) to CSI drivers via a Unix Domain Socket". Sidecars and driver share the socket "through an emptyDir volume"; kubelet and node plugin share it "via a HostPath volume".
| Component | Runs as | Watches / receives | Calls |
|---|---|---|---|
| external-provisioner | Sidecar in the controller Deployment | PVCs for its driver | CreateVolume, DeleteVolume |
| external-attacher | Sidecar in the controller Deployment | VolumeAttachment objects | ControllerPublishVolume / Unpublish |
| external-resizer | Sidecar in the controller Deployment | PVC size changes | ControllerExpandVolume |
| external-snapshotter (csi-snapshotter) | Sidecar in the controller Deployment | VolumeSnapshotContent | CreateSnapshot, DeleteSnapshot |
| node-driver-registrar | Sidecar in the node DaemonSet | - | Registers the driver socket with the kubelet |
| livenessprobe | Sidecar in both | - | Exposes driver health for probes |
| kubelet | Node | Pods assigned to the node | NodeStageVolume, NodePublishVolume, NodeExpandVolume |
Fix: when storage misbehaves, read the right logs: provisioning problems in csi-provisioner, attach problems in csi-attacher and VolumeAttachment status, mount problems in the node plugin and kubelet events on the Pod. Topology and CRDs for drivers you write are in Extending Kubernetes.
StatefulSet storage: volumeClaimTemplates and PVC retention Must-know
In plain words: A StatefulSet stamps out one PVC per replica from a template and always gives replica N its own claim back, wherever it is rescheduled.
Common misunderstanding: "Scaling a StatefulSet down frees the storage." By design, "Deleting and/or scaling a StatefulSet down will not delete the volumes associated with the StatefulSet. This is done to ensure data safety".
Definition: "For each VolumeClaimTemplate entry defined in a StatefulSet, each Pod receives one PersistentVolumeClaim", named <template>-<statefulset>-<ordinal> (data-cache-0). "If no StorageClass is specified, then the default StorageClass will be used." The PVs "are not deleted when the Pods, or StatefulSet are deleted. This must be done manually", unless .spec.persistentVolumeClaimRetentionPolicy says otherwise (stable v1.32): whenDeleted and whenScaled, each Retain (default) or Delete. Changing volumeClaimTemplates of an existing StatefulSet is not allowed (only new PVCs would see it); resize PVCs directly. The controller and its ordering guarantees are in Kubernetes Workloads.
StatefulSet cache: replicas 3 -> 2 -> 3, whenScaled: Delete
1 scale to 2: cache-2 terminated; then PVC data-cache-2 deleted (owner set to the condemned Pod)
2 reclaim policy of its PV decides the disk: gp3-retain -> Released and kept, gp3 -> deleted
3 scale to 3: new PVC data-cache-2 -> new empty volume -> shard 2 starts empty (its keys are cache misses)
with whenScaled: Retain (default): step 3 reattaches the old data-cache-2 with its old dataFix: Retain/Retain for databases, whenScaled: Delete for independent cache shards whose data can be lost (the example: three unreplicated Redis shards addressed by name, not a replicated Redis); a PodDisruptionBudget per StatefulSet; zone spread so one zone outage takes one replica. File: k8s/statefulset.yaml.
Local PersistentVolumes and topology Good to know
In plain words: A local PV is a disk physically inside one node, offered to Kubernetes as a PV pinned to that node: very fast, and gone with the node.
Common misunderstanding: "Local PV is hostPath with extra steps." The scheduler knows about it: "The system is aware of the volume's node constraints by looking at the node affinity on the PersistentVolume", which hostPath does not provide.
Definition: "Local volumes can only be used as a statically created PersistentVolume. Dynamic provisioning is not supported." "You must set a PersistentVolume nodeAffinity when using local volumes", and the class should use WaitForFirstConsumer with provisioner: kubernetes.io/no-provisioner. Availability is the node's: "If a node becomes unhealthy, then the local volume becomes inaccessible to the Pod." The sig-storage local static provisioner discovers disks under a directory and creates PVs. CloudNativePG recommends this shape for PostgreSQL: instances "should not share the storage and preferably use local volumes attached to the node they run on", with replication, not the disk, providing durability.
CloudNativePG on three nodes with one NVMe disk each, class local-nvme (no-provisioner, WaitForFirstConsumer)
1 the local static provisioner finds /mnt/disks/nvme0 on node-a, -b, -c and creates three PVs,
each with nodeAffinity kubernetes.io/hostname = its node
2 the operator creates PVCs orders-db-1..3; they stay Pending until their Pods are scheduled
3 scheduler places orders-db-1 on node-a and binds the PVC to node-a's PV (anti-affinity spreads the rest)
4 node-b dies: orders-db-2 cannot move (its PV is pinned to node-b); the operator fails over to a replica
5 node-b is replaced: the old PV is gone; the operator re-creates the instance on a new local PV
and re-clones it from the primary over streaming replicationReal scenarios: Kafka brokers on i4i/NVMe instances for throughput at low cost; a single-replica app on a local PV that was down for a day while its node was repaired; a node pool upgrade that recreates nodes and wipes every local PV, so the operator must re-clone all replicas; an Elasticsearch cluster where shards replicate, making node loss a non-event.
| Option | Dynamic? | Survives node loss? | Typical use |
|---|---|---|---|
local PV + no-provisioner class | No (admin or static provisioner) | No | Self-replicating databases and brokers |
| sig-storage local static provisioner | Discovers disks, creates PVs | No | Bare metal and NVMe node pools |
| Third-party local CSI drivers (OpenEBS LocalPV, TopoLVM) | Yes, with capacity tracking | No | Dynamic local storage |
hostPath | No | No | Never for app data: no scheduler awareness |
| Network block storage (EBS, PD) | Yes | Yes (re-attach in the same zone) | Single-instance state, simpler operations |
Fix: local PVs only for workloads that replicate themselves (PostgreSQL with streaming replication, Kafka, Cassandra, Elasticsearch) and tolerate losing a node's data.
Databases on Kubernetes: operators, managed vs in-cluster, backups, failover Important
In plain words: A database on Kubernetes is a StatefulSet plus a lot of knowledge: who is primary, how replicas follow, how backups and restores work, what to do when a node is drained. An operator is a controller that encodes that knowledge; a managed service moves it to your cloud provider.
Common misunderstanding: "Kubernetes is only for stateless apps" and its opposite, "a Helm chart with a StatefulSet is a production database." The CloudNativePG maintainer's CNCF post lists the first as a "Stateless mindset" problem, and the second skips failover, backups and upgrades entirely.
Definition: an operator watches custom resources (Cluster, Backup, ScheduledBackup) and reconciles Pods, PVCs, Services, Secrets and PDBs to match. Three PostgreSQL examples:
- CloudNativePG (CNCF project): one primary and hot standbys over streaming replication; Services
-rw("applications connect only to the primary instance of the cluster"),-roand-r; a "Shared-nothing architecture recommended"; it manages PVCs itself (no StatefulSet). Failover: after the primary fails for longer than.spec.failoverDelay(default 0 s), the controller stops WAL receivers, elects and promotes a replica, and "automatically updates the -rw service to point to the promoted primary". Backups: WAL archive plus base backups to object storage through the Barman Cloud plugin (native object-store support is "deprecated from 1.26 in favor of the Barman Cloud Plugin", and native support "is removed starting from 1.32.0"), or CSI volume snapshots; "Our recommendation is to always setup the WAL archive in production." PDBs: "Each PostgreSQL Cluster is equipped with two associated PodDisruptionBudget resources", and a drain of the primary's node triggers a switchover first. It generates the Secret<cluster>-appwithusername,password,uriand more. - Zalando postgres-operator: "easy to run highly-available PostgreSQL clusters on Kubernetes (K8s) powered by Patroni", configured through CRD manifests; logical backups to S3 or GCS, connection pooling with PgBouncer, "Live volume resize without pod restarts (AWS EBS, PVC)".
- Percona Operator for PostgreSQL ("based on Postgres Operator developed by Crunchy Data") and Percona Operator for MySQL (group replication with HAProxy or MySQL Router, or async replication with Orchestrator), with scheduled backups and PMM monitoring.
CloudNativePG cluster orders-db (3 instances, zones a/b/c), node drain of the primary's node in zone a
1 kubectl drain node-a -> eviction of orders-db-1 (primary) is blocked by the primary PDB
2 operator sees the node is being drained -> switchover: promote orders-db-2 (zone b)
3 orders-db-rw Service now selects orders-db-2; apps reconnect (brief connection errors)
4 orders-db-1 restarts as a replica and is then evictable (replica PDB allows one at a time)
5 WAL archiving continues from the new primary to s3://acme-pg-backups/orders/| Managed database (RDS, Cloud SQL, Azure Flexible Server) | In-cluster with an operator (CloudNativePG, Percona, Zalando) | |
|---|---|---|
| Failover, patching, backups | Provider's SLA and tooling | Operator, configured and upgraded by you |
| Latency to the app | Network hop out of the cluster | Same cluster, can use local NVMe |
| Cost | Premium per instance, no ops headcount | Node cost, plus Kubernetes and PostgreSQL skills |
| Portability | Tied to the provider | Same manifests on any cluster, on-prem too |
| Extensions, versions, superuser | Provider's allow-list | Anything you can put in an image |
| Blast radius of a cluster outage | Database unaffected | Database goes with the cluster (needs replica clusters / DR) |
| Skills needed | Cloud console + SQL | PostgreSQL internals, operator, storage, Kubernetes networking |
The CNCF post's advice before going in-cluster is to make sure of "PostgreSQL knowledge within your team or organization" and "A reliable operator to manage the entire lifecycle of a PostgreSQL database cluster in high availability", and to stay away from the temptation to lift-and-shift databases from traditional environments into Kubernetes, unless that is a conscious intermediate step.
Fix: default to managed unless you need portability, on-prem, local NVMe or many small databases; if in-cluster, use an operator, not a hand-made StatefulSet; always WAL archive to object storage in another failure domain; test restores (Backup, PITR & DR); keep the operator's PDBs on. File: k8s/cnpg-cluster.yaml. Replication theory: Replication & Failover.
Redis, RabbitMQ and Kafka operators: a preview Good to know
In plain words: The same operator idea exists for every stateful system: Strimzi for Kafka, the RabbitMQ Cluster Operator, and several Redis operators. They all end in StatefulSets (or operator-managed Pods) with volumeClaimTemplates, PDBs and Secrets for credentials.
Common misunderstanding: "A cache needs no persistence." Redis used as a queue or session store loses data on restart without AOF/RDB on a PVC; Redis used as a pure cache can run on emptyDir.
| System | Operator (project) | Storage pattern |
|---|---|---|
| Kafka | Strimzi (CNCF), Kafka and KafkaNodePool resources | JBOD of PVCs per broker; KRaft controllers; rack awareness by zone |
| RabbitMQ | RabbitMQ Cluster Operator (RabbitmqCluster) | One PVC per node; quorum queues replicate across nodes |
| Redis | OT-CONTAINER-KIT redis-operator, Spotahome redis-operator (Sentinel), Redis Enterprise | PVC per replica for AOF/RDB, or none for a cache |
| Messaging concepts | Messaging section | - |
Fix: pick the operator the project itself recommends, size PVCs for retention, and give each broker its own zone.
Mechanics
How the kubelet updates a mounted ConfigMap or Secret: the atomic writer
The kubelet writes ConfigMap, Secret, downward API and projected volumes with one helper, AtomicWriter (pkg/volume/util/atomic_writer.go). Its comment describes the layout: the visible files are symlinks into a ..data link, and the actual files live in a hidden timestamped directory that ..data points to. An update writes a complete new timestamped directory, creates ..data_tmp pointing at it, and then "The new data directory symlink is renamed to the data directory; rename is atomic." Finally it adds or removes the per-key symlinks and deletes the old directory. Each single path lookup therefore resolves to the old generation or the new one; but a reader that opens several keys one after another can straddle a swap and combine generations, which is why the Go ReadDir resolves ..data once, reads every key inside that one generation directory, and reads again if ..data moved meanwhile; and the same comment tells consumers to monitor the ..data symlink with inotify or fanotify rather than the files.
/etc/orders/config (what `ls -la` shows inside the container)
features -> ..data/features
log_level -> ..data/log_level
request_timeout -> ..data/request_timeout
..data -> ..2026_11_29_10_05_00.123456789
..2026_11_29_10_05_00.123456789/ (the real files, mode from defaultMode/items)Consequences you can rely on: (1) watch the directory; an inotify watch on log_level follows the symlink to a file in the old timestamped directory, which is deleted, never written; (2) because keys are symlinks, cp -r or a naive backup copies links, not contents; (3) a subPath mount bind-mounts the resolved file and therefore never sees the swap; (4) the ..-prefixed names are reserved ("AtomicWriter reserves the set of pathnames starting with .."), so do not name a key ..data.
Timing knobs
| Knob | Where | Default | Effect |
|---|---|---|---|
syncFrequency | KubeletConfiguration | 1m | Upper bound between volume refreshes for a Pod |
configMapAndSecretChangeDetectionStrategy | KubeletConfiguration | Watch | Watch, Cache (TTL) or Get (API on every sync) |
immutable | ConfigMap / Secret | false | true closes the kubelet watch; object cannot change |
defaultMode / items[].mode | Volume source | 0644 | File permissions of projected keys (Secrets: use 0400 or 0440 with fsGroup) |
optional | configMapKeyRef, secretKeyRef, volume sources | false | Start the Pod even if the object or key is missing |
expirationSeconds | Projected serviceAccountToken | 3600 (min 600) | Token lifetime; the kubelet refreshes it before expiry |
refreshInterval | ESO ExternalSecret | (set it) | How often ESO re-reads the provider; 0 = once |
--rotation-poll-interval | Secrets Store CSI driver | 2m | Minimum time between rotations when rotation is on |
reloader.stakater.com/auto | Workload annotation | off | Roll the workload on referenced ConfigMap/Secret change |
volumeBindingMode | StorageClass | Immediate | WaitForFirstConsumer for zonal or node-local storage |
reclaimPolicy | StorageClass | Delete | Retain for data you cannot re-create |
allowVolumeExpansion | StorageClass | false | Permit growing PVCs |
persistentVolumeClaimRetentionPolicy | StatefulSet | Retain / Retain | whenDeleted, whenScaled |
.spec.failoverDelay | CloudNativePG Cluster | 0 s | Wait before failover after a primary failure |
enablePDB | CloudNativePG Cluster | true | Operator-managed PodDisruptionBudgets |
PVC lifecycle and binding, step by step
PVC created (class gp3, WaitForFirstConsumer) phase Pending, no PV
1 Pod referencing it is created -> scheduler filters nodes by: free capacity, PVC topology,
CSI storage capacity (if the driver publishes it), node affinity of existing PVs
2 scheduler picks node-b and records the selected node on the PVC
3 external-provisioner sees it -> CreateVolume(name=pvc-<uid>, capacity, accessibility=zone b)
4 provisioner creates PV pvc-<uid> (claimRef -> PVC, nodeAffinity zone b, reclaimPolicy from class)
5 PV controller binds: PVC Bound, PV Bound
6 attach/detach controller creates VolumeAttachment(node-b) -> external-attacher -> ControllerPublish
7 kubelet: NodeStageVolume (format if empty, mount to a global dir), NodePublishVolume (bind into Pod)
8 container starts; fsGroup applied to files (fsGroupChangePolicy OnRootMismatch speeds this up)
Delete Pod: NodeUnpublish/Unstage, ControllerUnpublish; PVC stays Bound
Delete PVC: Delete -> DeleteVolume; Retain -> PV ReleasedErrors you will actually see
Strings in quotes below are copied from the Kubernetes source (pkg/kubelet/kuberuntime/kuberuntime_container.go, pkg/kubelet/kubelet_pods.go, pkg/scheduler/framework/plugins/volumebinding/) or the tool docs; the other rows describe the symptom without claiming exact wording.
Symptom (kubectl describe / events) | Meaning | Fix |
|---|---|---|
Container waiting with reason CreateContainerConfigError, message such as "couldn't find key %v in Secret %v/%v" or a not-found Secret | Env reference to a missing Secret or key | Create it (check namespace and ESO status) or mark optional: true |
Pod stuck ContainerCreating with a FailedMount event naming the Secret | Volume source missing | Same; volumes wait instead of failing the container |
FailedScheduling with "pod has unbound immediate PersistentVolumeClaims" | Immediate class could not provision, or no static PV matches | Check class name, provisioner logs, quotas |
FailedScheduling with "node(s) didn't match PersistentVolume's node affinity" | PV is in a zone/node with no schedulable capacity | Add capacity in that zone; use WaitForFirstConsumer for new volumes |
Multi-attach error event; new Pod stuck ContainerCreating | RWO disk still attached to another node | strategy: Recreate; wait for detach; check stuck VolumeAttachment |
ProvisioningFailed events from the CSI provisioner | Cloud API refused (quota, IAM, bad parameter) | Read csi-provisioner logs; fix IAM role or parameters |
PVC Pending with an event saying it waits for the first consumer | Normal for WaitForFirstConsumer | Create the Pod |
| PVC condition saying a file-system resize is pending | Disk grown, file system waits for the node | Happens when the Pod (re)mounts, or online on supporting drivers |
ExternalSecret in SecretSyncedError / SecretStore not Ready | Auth or path wrong at the provider | kubectl describe externalsecret; check Vault role / IAM policy |
| Pod evicted for exceeding its ephemeral-storage limit | emptyDir / logs exceeded limits | sizeLimit, log rotation, a real volume |
Go
The Go service (orders-api) shows the application half of this chapter: which settings it reads once from the environment, which it hot-reloads from a mounted ConfigMap, and how it reads a credential from a mounted Secret so rotation needs no restart. The module is stdlib plus github.com/fsnotify/fsnotify v1.10.1 (its go.mod declares go 1.23, so it builds in this module's go 1.24).
Before
The version most services start with: everything read once at start-up, the password from an env var, and a watch on the file itself, which goes quiet after the first kubelet update.
// Command before is the "Before" version of orders-api's config handling:
// it builds and runs, and in Kubernetes it never sees a config change.
package main
import (
"log"
"os"
"github.com/fsnotify/fsnotify"
)
var (
dbPassword = os.Getenv("DB_PASSWORD") // secretKeyRef: frozen until the Pod is replaced
logLevel = mustRead("/etc/orders/config/log_level")
)
func mustRead(p string) string {
b, err := os.ReadFile(p)
if err != nil {
log.Fatal(err)
}
return string(b) // trailing newline kept: "info\n" != "info"
}
func watch() {
w, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
// Watches the key's symlink target, a file in the OLD timestamped
// directory. The kubelet swaps ..data and deletes that directory: the
// watch reports the removal once and then goes quiet forever.
if err := w.Add("/etc/orders/config/log_level"); err != nil {
log.Fatal(err)
}
for ev := range w.Events {
logLevel = mustRead(ev.Name) // data race with readers, no validation, exits on a bad edit
}
}
func main() {
go watch()
log.Printf("log level %q, password set: %t", logLevel, dbPassword != "")
select {} // serve forever (HTTP server omitted)
}After
config.go: static settings from the environment (with the *_FILE convention), reloadable settings from one-file-per-key ConfigMap volumes read inside one resolved ..data generation (re-read if it moves mid-read), validation.
// Package config loads orders-api configuration the way Kubernetes delivers it:
//
// - static settings from environment variables (env, envFrom, configMapKeyRef,
// secretKeyRef). The kubelet resolves them once, when the container starts,
// so a change needs a new Pod (rollout);
// - reloadable settings from files in a mounted ConfigMap directory, which the
// kubelet refreshes in place (see Watch);
// - credentials from files in a mounted Secret directory (SecretFile), read
// on use so a rotated value is picked up without a restart.
package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
// Static is resolved once at start-up. Changing any of it means a rollout.
type Static struct {
Port string // PORT, default 8080
ConfigDir string // CONFIG_DIR, default /etc/orders/config (mounted ConfigMap)
DatabaseURL string // DATABASE_URL_FILE (preferred) or DATABASE_URL
}
// LoadStatic reads environment variables through getenv (os.Getenv in main,
// a map in tests). A *_FILE variable wins over the plain one, the convention
// used by many official images, so the value can come from a mounted Secret
// instead of the process environment.
func LoadStatic(getenv func(string) string) (Static, error) {
s := Static{
Port: getenv("PORT"),
ConfigDir: getenv("CONFIG_DIR"),
}
if s.Port == "" {
s.Port = "8080"
}
if s.ConfigDir == "" {
s.ConfigDir = "/etc/orders/config"
}
if p := getenv("DATABASE_URL_FILE"); p != "" {
b, err := os.ReadFile(p)
if err != nil {
return Static{}, fmt.Errorf("DATABASE_URL_FILE: %w", err)
}
s.DatabaseURL = strings.TrimSpace(string(b))
} else {
s.DatabaseURL = getenv("DATABASE_URL")
}
if s.DatabaseURL == "" {
return Static{}, errors.New("database URL missing: set DATABASE_URL_FILE or DATABASE_URL")
}
return s, nil
}
// Dynamic is re-read from the mounted ConfigMap directory while running.
type Dynamic struct {
LogLevel string `json:"log_level"`
RequestTimeout time.Duration `json:"request_timeout"`
Features map[string]bool `json:"features"`
}
// Defaults apply to keys that are absent from the ConfigMap.
func Defaults() Dynamic {
return Dynamic{LogLevel: "info", RequestTimeout: 5 * time.Second, Features: map[string]bool{}}
}
// afterRead is a test hook called between reading the keys and re-checking
// the generation; production code leaves it nil.
var afterRead func()
// ReadDir reads one file per key, which is how a ConfigMap volume projects
// its data: <dir>/log_level, <dir>/request_timeout, <dir>/features.
//
// In a kubelet-managed volume every key is a symlink through "..data", and an
// update swaps "..data" to a new timestamped directory. Opening the keys one
// by one could straddle a swap and mix two generations, so ReadDir resolves
// "..data" once, reads every key inside that one generation directory, and
// reads again if "..data" moved meanwhile. (A plain directory without
// "..data", as in local development, is read directly.)
// It returns the parsed config and the raw bytes (used to detect real changes).
func ReadDir(dir string) (Dynamic, []byte, error) {
for attempt := 0; attempt < 5; attempt++ {
gen := generation(dir)
base := dir
if gen != "" {
base = filepath.Join(dir, gen)
if filepath.IsAbs(gen) {
base = gen
}
}
vals, raw, err := readKeys(base)
if afterRead != nil {
afterRead()
}
if generation(dir) != gen {
continue // swapped while we were reading: read the new generation
}
if err != nil {
return Dynamic{}, nil, err
}
d, err := parse(vals)
if err != nil {
return Dynamic{}, nil, err
}
return d, raw, nil
}
return Dynamic{}, nil, errors.New("config directory kept changing while being read")
}
// generation returns the target of dir/..data, or "" if there is none.
func generation(dir string) string {
t, err := os.Readlink(filepath.Join(dir, "..data"))
if err != nil {
return ""
}
return t
}
var keys = []string{"log_level", "request_timeout", "features"}
func readKeys(base string) (map[string]string, []byte, error) {
vals := map[string]string{}
var raw strings.Builder
for _, key := range keys {
b, err := os.ReadFile(filepath.Join(base, key))
if errors.Is(err, os.ErrNotExist) {
continue // key absent from the ConfigMap: default applies
}
if err != nil {
return nil, nil, err
}
raw.WriteString(key + "=" + string(b) + "\n")
vals[key] = strings.TrimSpace(string(b))
}
return vals, []byte(raw.String()), nil
}
func parse(vals map[string]string) (Dynamic, error) {
d := Defaults()
if v, ok := vals["log_level"]; ok {
d.LogLevel = v
}
if v, ok := vals["request_timeout"]; ok {
t, err := time.ParseDuration(v)
if err != nil {
return Dynamic{}, fmt.Errorf("request_timeout: %w", err)
}
d.RequestTimeout = t
}
if v, ok := vals["features"]; ok {
f, err := parseFeatures(v)
if err != nil {
return Dynamic{}, err
}
d.Features = f
}
if err := d.Validate(); err != nil {
return Dynamic{}, err
}
return d, nil
}
// Validate rejects values that would break the service. A bad edit to the
// ConfigMap must not take a running Pod down: Watch keeps the last good value.
func (d Dynamic) Validate() error {
switch d.LogLevel {
case "debug", "info", "warn", "error":
default:
return fmt.Errorf("log_level %q: want debug, info, warn or error", d.LogLevel)
}
if d.RequestTimeout <= 0 || d.RequestTimeout > time.Minute {
return fmt.Errorf("request_timeout %s: want > 0 and <= 1m", d.RequestTimeout)
}
return nil
}
// parseFeatures reads "checkout_v2=true,gift_cards=false".
func parseFeatures(s string) (map[string]bool, error) {
out := map[string]bool{}
for _, part := range strings.Split(s, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
name, val, ok := strings.Cut(part, "=")
if !ok {
return nil, fmt.Errorf("features: %q is not name=bool", part)
}
b, err := strconv.ParseBool(strings.TrimSpace(val))
if err != nil {
return nil, fmt.Errorf("features: %q: %w", part, err)
}
out[strings.TrimSpace(name)] = b
}
return out, nil
}
// Names returns the enabled feature names, sorted (for logs and /config).
func (d Dynamic) Names() []string {
n := []string{}
for k, v := range d.Features {
if v {
n = append(n, k)
}
}
sort.Strings(n)
return n
}watch.go: a directory watch that ignores which event arrived, debounces the burst of one kubelet update, re-reads, compares bytes with the generation the Store holds, validates, and swaps an atomic.Pointer (keeping the last good config on a bad edit). Right after the watch is registered it reloads once, so an update projected before start-up is not lost.
package config
import (
"bytes"
"context"
"log/slog"
"sync/atomic"
"time"
"github.com/fsnotify/fsnotify"
)
// Store holds the current Dynamic config. Readers call Load on every use;
// the watcher swaps the pointer atomically, so a request sees either the old
// or the new config, never a half-updated one.
type Store struct {
cur atomic.Pointer[snapshot]
}
// snapshot is one applied generation: the parsed config and the raw bytes
// it was parsed from (nil when the origin is unknown, e.g. defaults).
type snapshot struct {
d Dynamic
raw []byte
}
// NewStore starts with d, origin unknown: the watcher applies whatever is on
// disk when it starts.
func NewStore(d Dynamic) *Store { return NewStoreFrom(d, nil) }
// NewStoreFrom starts with d parsed from raw (the bytes ReadDir returned).
func NewStoreFrom(d Dynamic, raw []byte) *Store {
s := &Store{}
s.cur.Store(&snapshot{d: d, raw: raw})
return s
}
// Load returns the current config.
func (s *Store) Load() Dynamic { return s.cur.Load().d }
func (s *Store) applied() []byte { return s.cur.Load().raw }
// Watcher reloads a mounted ConfigMap directory when the kubelet updates it.
//
// The kubelet never rewrites the visible files in place. Each key is a
// symlink "key -> ..data/key"; "..data" is itself a symlink to a hidden
// timestamped directory. An update writes a new timestamped directory, points
// "..data_tmp" at it and renames "..data_tmp" over "..data" (one atomic
// rename; see pkg/volume/util/atomic_writer.go). Watching the files themselves
// would miss that, so Watcher watches the directory, ignores which event
// arrived, waits for the burst to settle (Debounce), re-reads every key,
// and applies the result only if the bytes differ from the generation the
// Store holds and the config validates. Right after the watch is registered
// it does one reload, so an update projected before Run started (or between
// start-up and fsnotify.Add) is not lost.
type Watcher struct {
Dir string
Store *Store
Logger *slog.Logger
Debounce time.Duration // default 250ms
OnReload func(Dynamic) // called after a successful swap (optional)
OnError func(error) // called when a reload is rejected (optional)
OnReady func() // called once the directory watch is registered (optional)
}
// Run blocks until ctx is cancelled. It returns an error only if the watch
// cannot be set up (for example the directory does not exist).
func (w *Watcher) Run(ctx context.Context) error {
if w.Debounce == 0 {
w.Debounce = 250 * time.Millisecond
}
if w.Logger == nil {
w.Logger = slog.Default()
}
fw, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer fw.Close()
if err := fw.Add(w.Dir); err != nil {
return err
}
w.reload() // catch up with anything projected before the watch existed
if w.OnReady != nil {
w.OnReady()
}
timer := time.NewTimer(time.Hour)
timer.Stop()
defer timer.Stop()
for {
select {
case <-ctx.Done():
return nil
case ev, ok := <-fw.Events:
if !ok {
return nil
}
w.Logger.Debug("config dir event", "name", ev.Name, "op", ev.Op.String())
timer.Reset(w.Debounce) // coalesce the burst of events of one update
case err, ok := <-fw.Errors:
if !ok {
return nil
}
w.Logger.Warn("config watch error", "err", err)
case <-timer.C:
w.reload()
}
}
}
func (w *Watcher) reload() {
d, raw, err := ReadDir(w.Dir)
if err != nil {
// Keep serving with the last good config; a bad ConfigMap edit must
// not crash-loop every replica at once.
w.Logger.Error("config reload rejected, keeping previous config", "err", err)
if w.OnError != nil {
w.OnError(err)
}
return
}
if bytes.Equal(raw, w.Store.applied()) {
return // nothing changed (e.g. chmod, cleanup of the old dir, start-up with current data)
}
w.Store.cur.Store(&snapshot{d: d, raw: raw})
w.Logger.Info("config reloaded", "log_level", d.LogLevel,
"request_timeout", d.RequestTimeout.String(), "features", d.Names())
if w.OnReload != nil {
w.OnReload(d)
}
}secretfile.go: a credential read from a mounted Secret on use, with a short cache, so rotation by ESO, the CSI driver or a human reaches the process without a restart.
package config
import (
"fmt"
"os"
"strings"
"sync"
"time"
)
// SecretFile reads a credential from a mounted Secret volume on use, with a
// short cache. When the Secret is rotated (by hand, by External Secrets
// Operator or by the Secrets Store CSI driver), the kubelet swaps the files
// and the next read after the cache expires returns the new value; an
// environment variable would keep the old one until the Pod is replaced.
type SecretFile struct {
Path string
TTL time.Duration // 0 means read the file on every call
mu sync.Mutex
value string
readAt time.Time
nowFunc func() time.Time // for tests
}
func (s *SecretFile) now() time.Time {
if s.nowFunc != nil {
return s.nowFunc()
}
return time.Now()
}
// Value returns the trimmed file content.
func (s *SecretFile) Value() (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.value != "" && s.TTL > 0 && s.now().Sub(s.readAt) < s.TTL {
return s.value, nil
}
b, err := os.ReadFile(s.Path)
if err != nil {
return "", fmt.Errorf("secret %s: %w", s.Path, err)
}
s.value = strings.TrimSpace(string(b))
s.readAt = s.now()
return s.value, nil
}dbconn: a driver.Connector that re-reads the DSN from that SecretFile for every new connection, with a test that rotates the file and checks the next dial uses the new credential:
// Package dbconn makes database/sql pick up a rotated credential.
//
// sql.Open(driver, dsn) stores the DSN once; SetConnMaxLifetime only retires
// old connections, and the pool would dial new ones with the OLD password.
// A driver.Connector is asked for every new physical connection, so this one
// re-reads the DSN from a mounted Secret file (config.SecretFile) each time.
package dbconn
import (
"context"
"database/sql"
"database/sql/driver"
"time"
"academy/kubernetes-config-secrets-storage/config"
)
// Connector dials with whatever DSN the Secret file holds right now.
type Connector struct {
Secret *config.SecretFile // e.g. /etc/orders/secrets/database-url, TTL 30s
Dialer driver.Driver // e.g. the pgx stdlib driver
}
// Connect implements driver.Connector.
func (c *Connector) Connect(context.Context) (driver.Conn, error) {
dsn, err := c.Secret.Value()
if err != nil {
return nil, err
}
return c.Dialer.Open(dsn)
}
// Driver implements driver.Connector.
func (c *Connector) Driver() driver.Driver { return c.Dialer }
// Open returns a pool whose connections live at most maxLifetime, so after a
// rotation every connection is re-dialled (with the new DSN) within that time.
func Open(c *Connector, maxLifetime time.Duration) *sql.DB {
db := sql.OpenDB(c)
db.SetConnMaxLifetime(maxLifetime)
return db
}package dbconn
import (
"database/sql/driver"
"errors"
"os"
"path/filepath"
"sync"
"testing"
"academy/kubernetes-config-secrets-storage/config"
)
// fakeDriver records the DSN of every new connection.
type fakeDriver struct {
mu sync.Mutex
dsns []string
}
func (f *fakeDriver) Open(dsn string) (driver.Conn, error) {
f.mu.Lock()
f.dsns = append(f.dsns, dsn)
f.mu.Unlock()
return fakeConn{}, nil
}
func (f *fakeDriver) last() string {
f.mu.Lock()
defer f.mu.Unlock()
return f.dsns[len(f.dsns)-1]
}
type fakeConn struct{}
func (fakeConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("not used") }
func (fakeConn) Close() error { return nil }
func (fakeConn) Begin() (driver.Tx, error) { return nil, errors.New("not used") }
func TestNewConnectionsUseRotatedSecret(t *testing.T) {
path := filepath.Join(t.TempDir(), "database-url")
if err := os.WriteFile(path, []byte("postgres://orders:v1@db/orders\n"), 0o400); err != nil {
t.Fatal(err)
}
fd := &fakeDriver{}
db := Open(&Connector{Secret: &config.SecretFile{Path: path}, Dialer: fd}, 0)
defer db.Close()
db.SetMaxIdleConns(0) // every Ping dials a new connection
if err := db.Ping(); err != nil {
t.Fatal(err)
}
if got := fd.last(); got != "postgres://orders:v1@db/orders" {
t.Fatalf("first dial DSN = %q", got)
}
// Rotation: the kubelet (or ESO + kubelet) replaces the file content.
if err := os.Chmod(path, 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("postgres://orders:v2@db/orders\n"), 0o400); err != nil {
t.Fatal(err)
}
if err := db.Ping(); err != nil {
t.Fatal(err)
}
if got := fd.last(); got != "postgres://orders:v2@db/orders" {
t.Fatalf("dial after rotation DSN = %q, want the v2 credential", got)
}
}The tests reproduce the kubelet's atomic writer (new timestamped directory, ..data_tmp, rename over ..data) with real symlinks, cover a swap in the middle of ReadDir and a change projected before the watcher starts, and poll with a deadline:
package config
import (
"context"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
)
// projectAtomically mimics the kubelet's AtomicWriter for a ConfigMap or
// Secret volume: write the payload into a new hidden timestamped directory,
// point "..data_tmp" at it, rename "..data_tmp" over "..data" (atomic), make
// sure every key is a symlink "key -> ..data/key", then remove the previous
// timestamped directory.
func projectAtomically(t *testing.T, dir string, payload map[string]string) {
t.Helper()
old, _ := os.Readlink(filepath.Join(dir, "..data"))
ts := fmt.Sprintf("..%d", time.Now().UnixNano())
if err := os.Mkdir(filepath.Join(dir, ts), 0o755); err != nil {
t.Fatal(err)
}
for k, v := range payload {
if err := os.WriteFile(filepath.Join(dir, ts, k), []byte(v), 0o644); err != nil {
t.Fatal(err)
}
}
tmp := filepath.Join(dir, "..data_tmp")
if err := os.Symlink(ts, tmp); err != nil {
t.Fatal(err)
}
if err := os.Rename(tmp, filepath.Join(dir, "..data")); err != nil {
t.Fatal(err)
}
for k := range payload {
link := filepath.Join(dir, k)
if _, err := os.Lstat(link); os.IsNotExist(err) {
if err := os.Symlink(filepath.Join("..data", k), link); err != nil {
t.Fatal(err)
}
}
}
if old != "" {
_ = os.RemoveAll(filepath.Join(dir, old))
}
}
func quietLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
// eventually polls cond until it is true or the deadline passes.
func eventually(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("timed out waiting for %s", what)
}
func TestLoadStaticPrefersFile(t *testing.T) {
f := filepath.Join(t.TempDir(), "database-url")
if err := os.WriteFile(f, []byte("postgres://app@orders-db-rw:5432/app\n"), 0o400); err != nil {
t.Fatal(err)
}
env := map[string]string{
"DATABASE_URL_FILE": f,
"DATABASE_URL": "postgres://ignored",
}
s, err := LoadStatic(func(k string) string { return env[k] })
if err != nil {
t.Fatal(err)
}
if s.DatabaseURL != "postgres://app@orders-db-rw:5432/app" {
t.Fatalf("DatabaseURL = %q (trailing newline must be trimmed, file must win)", s.DatabaseURL)
}
if s.Port != "8080" || s.ConfigDir != "/etc/orders/config" {
t.Fatalf("defaults not applied: %+v", s)
}
}
func TestLoadStaticMissingDatabase(t *testing.T) {
if _, err := LoadStatic(func(string) string { return "" }); err == nil {
t.Fatal("want an error when no database URL is configured")
}
}
func TestReadDirDefaultsAndValues(t *testing.T) {
dir := t.TempDir()
d, _, err := ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if d.LogLevel != "info" || d.RequestTimeout != 5*time.Second {
t.Fatalf("defaults = %+v", d)
}
projectAtomically(t, dir, map[string]string{
"log_level": "warn\n",
"request_timeout": "2s",
"features": "checkout_v2=true, gift_cards=false",
})
d, _, err = ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if d.LogLevel != "warn" || d.RequestTimeout != 2*time.Second {
t.Fatalf("parsed = %+v", d)
}
if got := strings.Join(d.Names(), ","); got != "checkout_v2" {
t.Fatalf("enabled features = %q", got)
}
}
func TestReadDirRejectsInvalid(t *testing.T) {
for name, payload := range map[string]map[string]string{
"level": {"log_level": "verbose"},
"timeout": {"request_timeout": "5 minutes"},
"range": {"request_timeout": "2m"},
"feature": {"features": "checkout_v2"},
} {
t.Run(name, func(t *testing.T) {
dir := t.TempDir()
projectAtomically(t, dir, payload)
if _, _, err := ReadDir(dir); err == nil {
t.Fatalf("want an error for %v", payload)
}
})
}
}
func startWatcher(t *testing.T, dir string, store *Store, onErr func(error)) *atomic.Int32 {
t.Helper()
var reloads atomic.Int32
ready := make(chan struct{})
w := &Watcher{
Dir: dir, Store: store, Logger: quietLogger(), Debounce: 50 * time.Millisecond,
OnReload: func(Dynamic) { reloads.Add(1) },
OnError: onErr,
OnReady: func() { close(ready) },
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- w.Run(ctx) }()
t.Cleanup(func() {
cancel()
if err := <-done; err != nil {
t.Errorf("Run: %v", err)
}
})
select { // wait until the directory watch is registered, not a fixed sleep
case <-ready:
case <-time.After(5 * time.Second):
t.Fatal("watcher did not start")
}
return &reloads
}
func TestWatcherPicksUpAtomicSwap(t *testing.T) {
dir := t.TempDir()
projectAtomically(t, dir, map[string]string{"log_level": "info", "features": "checkout_v2=false"})
initial, raw, err := ReadDir(dir)
if err != nil {
t.Fatal(err)
}
store := NewStoreFrom(initial, raw)
reloads := startWatcher(t, dir, store, nil)
projectAtomically(t, dir, map[string]string{"log_level": "debug", "features": "checkout_v2=true"})
eventually(t, "log_level=debug", func() bool { return store.Load().LogLevel == "debug" })
if !store.Load().Features["checkout_v2"] {
t.Fatal("feature flag not reloaded")
}
if n := reloads.Load(); n != 1 {
t.Fatalf("reloads = %d, want exactly 1 (the burst of events must be coalesced)", n)
}
}
func TestWatcherKeepsLastGoodConfig(t *testing.T) {
dir := t.TempDir()
projectAtomically(t, dir, map[string]string{"log_level": "info"})
store := NewStore(Defaults())
var rejected atomic.Int32
startWatcher(t, dir, store, func(error) { rejected.Add(1) })
projectAtomically(t, dir, map[string]string{"log_level": "loud"})
eventually(t, "rejection", func() bool { return rejected.Load() > 0 })
if got := store.Load().LogLevel; got != "info" {
t.Fatalf("after a bad edit LogLevel = %q, want the previous good value", got)
}
projectAtomically(t, dir, map[string]string{"log_level": "error"})
eventually(t, "log_level=error", func() bool { return store.Load().LogLevel == "error" })
}
func TestWatcherMissingDir(t *testing.T) {
w := &Watcher{Dir: filepath.Join(t.TempDir(), "absent"), Store: NewStore(Defaults()), Logger: quietLogger()}
if err := w.Run(context.Background()); err == nil {
t.Fatal("want an error for a directory that does not exist")
}
}
func TestSecretFileSeesRotation(t *testing.T) {
dir := t.TempDir()
projectAtomically(t, dir, map[string]string{"password": "s3cret-v1\n"})
now := time.Unix(1_700_000_000, 0)
s := &SecretFile{Path: filepath.Join(dir, "password"), TTL: 30 * time.Second, nowFunc: func() time.Time { return now }}
if v, err := s.Value(); err != nil || v != "s3cret-v1" {
t.Fatalf("Value = %q, %v", v, err)
}
projectAtomically(t, dir, map[string]string{"password": "s3cret-v2\n"})
if v, _ := s.Value(); v != "s3cret-v1" {
t.Fatalf("within TTL Value = %q, want the cached v1", v)
}
now = now.Add(31 * time.Second)
if v, _ := s.Value(); v != "s3cret-v2" {
t.Fatalf("after TTL Value = %q, want the rotated v2", v)
}
}
func TestReadDirUsesOneGeneration(t *testing.T) {
dir := t.TempDir()
projectAtomically(t, dir, map[string]string{"log_level": "info", "request_timeout": "5s"})
// Point the visible request_timeout link at a stale generation: a reader
// that opened keys one by one through their own links would mix values.
stale := filepath.Join(dir, "..stale")
if err := os.Mkdir(stale, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(stale, "request_timeout"), []byte("9s"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Remove(filepath.Join(dir, "request_timeout")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join("..stale", "request_timeout"), filepath.Join(dir, "request_timeout")); err != nil {
t.Fatal(err)
}
d, _, err := ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if d.RequestTimeout != 5*time.Second {
t.Fatalf("RequestTimeout = %s, want 5s from the ..data generation", d.RequestTimeout)
}
}
func TestReadDirRereadsAfterSwapMidRead(t *testing.T) {
dir := t.TempDir()
projectAtomically(t, dir, map[string]string{"log_level": "info", "request_timeout": "5s"})
swapped := false
afterRead = func() {
if !swapped { // swap once, between reading the keys and the re-check
swapped = true
projectAtomically(t, dir, map[string]string{"log_level": "debug", "request_timeout": "2s"})
}
}
t.Cleanup(func() { afterRead = nil })
d, _, err := ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if d.LogLevel != "debug" || d.RequestTimeout != 2*time.Second {
t.Fatalf("got %+v, want the whole new generation (debug, 2s)", d)
}
}
func TestWatcherAppliesChangeMadeBeforeStart(t *testing.T) {
dir := t.TempDir()
projectAtomically(t, dir, map[string]string{"log_level": "info"})
a, raw, err := ReadDir(dir)
if err != nil {
t.Fatal(err)
}
store := NewStoreFrom(a, raw) // generation A applied
// B is projected after the store was filled but before the watch exists.
projectAtomically(t, dir, map[string]string{"log_level": "warn"})
startWatcher(t, dir, store, nil)
eventually(t, "log_level=warn without any further event", func() bool { return store.Load().LogLevel == "warn" })
}main.go wires it up: slog.LevelVar changes the log level live, /config shows the reloadable values and never secrets, SIGTERM drains the server.
// Command orders-api shows how a Go service consumes Kubernetes configuration:
//
// - PORT and DATABASE_URL_FILE come from the environment (set in the Pod
// spec with env / envFrom / configMapKeyRef / secretKeyRef); they are read
// once, so changing them needs a rollout;
// - log level, request timeout and feature flags come from files in a
// mounted ConfigMap (CONFIG_DIR) and are hot-reloaded by config.Watcher;
// - /config shows the live reloadable settings and never prints secrets.
package main
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"academy/kubernetes-config-secrets-storage/config"
)
func main() {
level := new(slog.LevelVar) // changed at runtime by the watcher
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
if err := run(logger, level, os.Getenv); err != nil {
logger.Error("exit", "err", err)
os.Exit(1)
}
}
func run(logger *slog.Logger, level *slog.LevelVar, getenv func(string) string) error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
static, err := config.LoadStatic(getenv)
if err != nil {
return err // fail fast: a missing Secret should stop the rollout, not limp on
}
dyn, raw, err := config.ReadDir(static.ConfigDir)
if err != nil {
return err
}
applyLevel(level, dyn.LogLevel)
store := config.NewStoreFrom(dyn, raw)
w := &config.Watcher{
Dir: static.ConfigDir, Store: store, Logger: logger,
OnReload: func(d config.Dynamic) { applyLevel(level, d.LogLevel) },
}
go func() {
if err := w.Run(ctx); err != nil {
logger.Error("config watcher stopped", "err", err)
}
}()
srv := &http.Server{
Addr: net.JoinHostPort("", static.Port),
Handler: routes(store),
ReadHeaderTimeout: 5 * time.Second,
}
errc := make(chan error, 1)
go func() { errc <- srv.ListenAndServe() }()
logger.Info("listening", "addr", srv.Addr, "config_dir", static.ConfigDir)
select {
case err := <-errc:
return err
case <-ctx.Done():
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
func routes(store *config.Store) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("GET /config", func(w http.ResponseWriter, _ *http.Request) {
d := store.Load()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"log_level": d.LogLevel,
"request_timeout": d.RequestTimeout.String(),
"features": d.Names(),
})
})
return mux
}
func applyLevel(v *slog.LevelVar, s string) {
var l slog.Level
if err := l.UnmarshalText([]byte(s)); err == nil {
v.Set(l)
}
}package main
import (
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"time"
"academy/kubernetes-config-secrets-storage/config"
)
func TestConfigEndpointShowsLiveValuesOnly(t *testing.T) {
store := config.NewStore(config.Dynamic{
LogLevel: "warn", RequestTimeout: 3 * time.Second,
Features: map[string]bool{"checkout_v2": true, "gift_cards": false},
})
rec := httptest.NewRecorder()
routes(store).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/config", nil))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["log_level"] != "warn" || body["request_timeout"] != "3s" {
t.Fatalf("body = %v", body)
}
if _, leaked := body["database_url"]; leaked {
t.Fatal("/config must never expose credentials")
}
}
func TestApplyLevel(t *testing.T) {
v := new(slog.LevelVar)
applyLevel(v, "debug")
if v.Level() != slog.LevelDebug {
t.Fatalf("level = %v", v.Level())
}
applyLevel(v, "nonsense") // ignored: the watcher validates before this point
if v.Level() != slog.LevelDebug {
t.Fatalf("level changed on invalid input: %v", v.Level())
}
}module academy/kubernetes-config-secrets-storage
go 1.24
require github.com/fsnotify/fsnotify v1.10.1
require golang.org/x/sys v0.13.0 // indirectA shell script that performs the same symlink swap as the kubelet, used in the Lab to exercise the watcher without a cluster:
#!/usr/bin/env bash
# project.sh DIR key=value [key=value ...]
# Mimics how the kubelet updates a ConfigMap/Secret volume (AtomicWriter):
# new hidden timestamped dir -> ..data_tmp symlink -> atomic rename over ..data
# -> one "key -> ..data/key" symlink per key -> remove the previous dir.
# Used by the lab to exercise the Go watcher on a laptop, without Kubernetes.
set -euo pipefail
dir=$1; shift
mkdir -p "$dir"
old=$(readlink "$dir/..data" 2>/dev/null || true)
ts="..$(date +%Y_%m_%d_%H_%M_%S).$RANDOM"
mkdir "$dir/$ts"
for kv in "$@"; do
printf '%s' "${kv#*=}" > "$dir/$ts/${kv%%=*}"
done
ln -s "$ts" "$dir/..data_tmp"
# rename(2) is the atomic step; never follow the old ..data link into its dir:
# GNU mv spells that -T, BSD/macOS mv spells it -h.
if mv --version >/dev/null 2>&1; then mv -Tf "$dir/..data_tmp" "$dir/..data"
else mv -hf "$dir/..data_tmp" "$dir/..data"; fi
for kv in "$@"; do
key=${kv%%=*}
[ -L "$dir/$key" ] || ln -s "..data/$key" "$dir/$key"
done
if [ -n "$old" ]; then rm -rf "${dir:?}/$old"; fiThe manifests that feed it. ConfigMaps (env-style, file-style, immutable):
# orders-api configuration (namespace: shop).
# Two ConfigMaps on purpose:
# orders-env -> consumed as environment variables (read once at container start)
# orders-config -> mounted as files (refreshed in place by the kubelet; the Go
# watcher hot-reloads log_level, request_timeout and features)
apiVersion: v1
kind: ConfigMap
metadata:
name: orders-env
namespace: shop
data:
PORT: "8080" # quote numbers: data values must be strings
CONFIG_DIR: /etc/orders/config
OTEL_SERVICE_NAME: orders-api
---
apiVersion: v1
kind: ConfigMap
metadata:
name: orders-config
namespace: shop
labels:
app.kubernetes.io/name: orders-api
data:
# one key = one file under the mount path
log_level: info
request_timeout: 5s
features: checkout_v2=false,gift_cards=true
# a whole file is just a key whose value is multi-line text
nginx-snippet.conf: |
client_max_body_size 20m;
proxy_read_timeout 30s;
---
# Immutable variant: the name carries a version (or a content hash), the Pod
# template points at the new name, and the change rolls out like an image bump.
# The kubelet closes its watch on immutable objects (less kube-apiserver load),
# and nobody can edit it in place by accident; only delete and recreate.
apiVersion: v1
kind: ConfigMap
metadata:
name: orders-config-v7
namespace: shop
immutable: true
data:
log_level: info
request_timeout: 5s
features: checkout_v2=true,gift_cards=trueSecrets of the main types (placeholders only):
# Secrets for orders-api. NEVER commit real values like this: in Git they go
# through Sealed Secrets or SOPS, or they never live in Git at all (External
# Secrets Operator, Secrets Store CSI driver). These manifests show the shapes.
#
# Opaque (the default type). stringData takes plain text; the API server
# stores it base64-encoded under .data. base64 is an encoding, not encryption.
apiVersion: v1
kind: Secret
metadata:
name: orders-db
namespace: shop
type: Opaque
stringData:
database-url: postgres://orders:change-me@orders-db-rw.shop.svc:5432/orders?sslmode=require
username: orders
password: change-me
---
# kubernetes.io/tls (shape only, so this file still applies as is): the API
# server requires both keys tls.crt and tls.key. Usually written by
# cert-manager, or created from real PEM files:
# kubectl create secret tls orders-tls --cert=tls.crt --key=tls.key -n shop
# which produces:
# type: kubernetes.io/tls
# data:
# tls.crt: <base64 of the PEM certificate>
# tls.key: <base64 of the PEM private key>
---
# kubernetes.io/dockerconfigjson: registry credentials for imagePullSecrets.
# kubectl create secret docker-registry ghcr-pull -n shop \
# --docker-server=ghcr.io --docker-username=acme-bot --docker-password="$GHCR_TOKEN"
apiVersion: v1
kind: Secret
metadata:
name: ghcr-pull
namespace: shop
type: kubernetes.io/dockerconfigjson
data:
.dockerconfigjson: eyJhdXRocyI6e319 # base64 of {"auths":{}} (placeholder)
---
# Immutable Secret: rotate by creating orders-db-v2 and rolling the Deployment.
apiVersion: v1
kind: Secret
metadata:
name: orders-db-v1
namespace: shop
type: Opaque
immutable: true
stringData:
password: change-meThe Deployment, with every consumption form annotated by when it sees a change:
# orders-api Deployment: every way a Pod can consume ConfigMaps and Secrets,
# each line annotated with WHEN the container sees a change.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
namespace: shop
annotations:
# Option A (controller): Stakater Reloader rolls the Deployment when the
# NAMED ConfigMap changes. Only orders-env (env vars) needs a rollout;
# orders-config and orders-db are hot-reloaded from files, so they are
# deliberately not listed (`auto: "true"` would roll on those too).
configmap.reloader.stakater.com/reload: "orders-env"
spec:
replicas: 3
selector:
matchLabels: { app.kubernetes.io/name: orders-api }
template:
metadata:
labels: { app.kubernetes.io/name: orders-api }
annotations:
# Option B (templating): Helm renders a hash of the ConfigMap into the
# Pod template, so any config change is a template change -> rollout:
# checksum/config: <sha256 of templates/configmap.yaml>
# (the exact Helm expression is in the page; it is not valid plain YAML)
checksum/config: "3f1c9e2d0b7a" # placeholder value
spec:
serviceAccountName: orders-api
automountServiceAccountToken: false # the projected token below replaces it
imagePullSecrets:
- name: ghcr-pull # kubernetes.io/dockerconfigjson Secret
securityContext:
runAsNonRoot: true
runAsUser: 65532
fsGroup: 65532 # group-owns mounted volume files
containers:
- name: orders-api
image: ghcr.io/acme/orders-api@sha256:0000000000000000000000000000000000000000000000000000000000000000
ports: [{ name: http, containerPort: 8080 }]
# 1. envFrom: every key of the ConfigMap becomes a variable. Read ONCE at start.
envFrom:
- configMapRef: { name: orders-env }
env:
# 2. One key, renamed, from a ConfigMap. Read once at start.
- name: APP_SERVICE_NAME
valueFrom:
configMapKeyRef: { name: orders-env, key: OTEL_SERVICE_NAME }
# 3. One key from a Secret as an env var: visible in /proc/<pid>/environ,
# inherited by child processes, frozen until the Pod is replaced.
- name: DB_USERNAME
valueFrom:
secretKeyRef: { name: orders-db, key: username }
# 4. Preferred for credentials: point at a FILE from a mounted Secret.
- name: DATABASE_URL_FILE
value: /etc/orders/secrets/database-url
# 5. Downward API as env: Pod facts known at start.
- name: POD_NAME
valueFrom: { fieldRef: { fieldPath: metadata.name } }
- name: MEMORY_LIMIT
valueFrom: { resourceFieldRef: { resource: limits.memory } }
volumeMounts:
# 6. Whole ConfigMap as a directory: refreshed in place (atomic ..data swap).
- name: config
mountPath: /etc/orders/config
readOnly: true
# 7. Secret as files on tmpfs: refreshed in place, never written to node disk.
- name: db-secret
mountPath: /etc/orders/secrets
readOnly: true
# 8. subPath: one file placed into an existing directory. It is a bind
# mount of the file and is NEVER updated when the ConfigMap changes.
- name: config
mountPath: /etc/nginx/conf.d/tuning.conf
subPath: nginx-snippet.conf
readOnly: true
# 9. Projected volume: several sources in one directory.
- name: pod-info
mountPath: /etc/podinfo
readOnly: true
# 10. Scratch space; gone when the Pod leaves the node.
- name: tmp
mountPath: /tmp
resources:
requests: { cpu: 100m, memory: 128Mi, ephemeral-storage: 256Mi }
limits: { memory: 256Mi, ephemeral-storage: 1Gi }
readinessProbe:
httpGet: { path: /healthz, port: http }
volumes:
- name: config
configMap:
name: orders-config
- name: db-secret
secret:
secretName: orders-db
defaultMode: 0440 # octal in YAML; files are group-readable via fsGroup
items: # project only what this container needs
- key: database-url
path: database-url
- name: pod-info
projected:
sources:
- downwardAPI:
items:
- path: labels
fieldRef: { fieldPath: metadata.labels }
- serviceAccountToken: # short-lived, audience-bound, auto-rotated by the kubelet
audience: vault
expirationSeconds: 3600
path: vault-token
- configMap:
name: orders-config
items: [{ key: features, path: features }]
- name: tmp
emptyDir:
sizeLimit: 256Mi # counts against node ephemeral storageWith Helm, the checksum annotation in the chart's Deployment template (the expression from Helm's tips page; it is a template, not plain YAML):
# templates/deployment.yaml (Helm chart excerpt)
spec:
template:
metadata:
annotations:
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}Least-privilege RBAC and the encryption config for the API server:
# RBAC for Secrets: least privilege.
# The app itself (ServiceAccount orders-api) gets NO Secret permissions: the
# kubelet mounts Secrets for it. Only a component that really calls the API
# for a Secret gets a Role, here a rotation Job (orders-db-rotator).
# - get on a NAMED Secret is the narrowest grant there is.
# - list or watch on secrets reveals the CONTENT of every Secret in the
# namespace (a list response carries the data), so never grant them to apps.
# - create on pods (or Deployments, Jobs...) in a namespace is indirect read
# access to every Secret there: the new Pod can mount any of them.
apiVersion: v1
kind: ServiceAccount
metadata:
name: orders-api
namespace: shop
automountServiceAccountToken: false # no Role is bound to it
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: orders-db-rotator
namespace: shop
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: orders-db-rotator
namespace: shop
rules:
- apiGroups: [""]
resources: ["secrets"]
resourceNames: ["orders-db"] # only this object
verbs: ["get", "update"] # read and replace this one Secret; no list, no watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: orders-db-rotator
namespace: shop
subjects:
- kind: ServiceAccount
name: orders-db-rotator
namespace: shop
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: orders-db-rotator
---
# The anti-pattern, for contrast (do not apply): a "read-only" role that can
# read every Secret in the namespace through list/watch.
# rules:
# - apiGroups: [""]
# resources: ["secrets", "configmaps"]
# verbs: ["get", "list", "watch"]# /etc/kubernetes/enc/enc.yaml on every control-plane node, passed to
# kube-apiserver with --encryption-provider-config=/etc/kubernetes/enc/enc.yaml
# (managed clusters: EKS/GKE/AKS expose this as "envelope encryption with a
# cloud KMS key" instead of a file you edit).
#
# The FIRST provider encrypts new writes; every provider is tried in order on
# reads. identity = plain text, so it may only appear as a later fallback
# while existing data is being re-encrypted. After changing this file, restart
# all API servers and rewrite every Secret:
# kubectl get secrets --all-namespaces -o json | kubectl replace -f -
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources:
- secrets
- configmaps # optional; config can leak hostnames too
providers:
- kms: # KMS v2: envelope encryption, KEK held in the external KMS
apiVersion: v2
name: cloud-kms
endpoint: unix:///var/run/kmsplugin/socket.sock # local gRPC KMS plugin
timeout: 3s
- aescbc: # previous provider, kept so old data stays readable
keys:
- name: key1
secret: <BASE 64 ENCODED 32-BYTE KEY>
- identity: {} # reads not-yet-encrypted objects during migrationSecrets from outside the cluster: ESO (Vault and AWS Secrets Manager), the Secrets Store CSI driver, and the two GitOps options:
# External Secrets Operator (ESO): the secret lives in Vault or a cloud secret
# manager; ESO copies it into a normal Kubernetes Secret and keeps it in sync.
# SecretStore = HOW to reach the provider (namespaced);
# ExternalSecret = WHAT to fetch and which Secret to write.
#
# 1) Vault, Kubernetes auth: ESO presents the orders-api ServiceAccount token,
# Vault validates it with the TokenReview API and maps it to a Vault role.
apiVersion: external-secrets.io/v1
kind: SecretStore
metadata:
name: vault
namespace: shop
spec:
provider:
vault:
server: "https://vault.acme.internal:8200"
path: "secret" # KV mount
version: "v2"
auth:
kubernetes:
mountPath: "kubernetes"
role: "orders-api"
serviceAccountRef:
name: "orders-api"
audiences: ["vault"] # Vault 1.21+ requires an audience on the role
---
# 2) AWS Secrets Manager for the whole cluster with EKS Pod Identity: the ESO
# controller's own ServiceAccount has a Pod Identity association, and the
# store has NO auth section. serviceAccountRef must not be used with Pod
# Identity (ESO cannot impersonate Pod-Identity-bound accounts).
# With IRSA instead, add: auth: { jwt: { serviceAccountRef: { name: ..., namespace: ... } } }
# ClusterSecretStore can be referenced from any namespace: restrict who may use it.
apiVersion: external-secrets.io/v1
kind: ClusterSecretStore
metadata:
name: aws-secretsmanager
spec:
provider:
aws:
service: SecretsManager
region: eu-central-1
---
# 3) The ExternalSecret: fetch two properties from Vault, write Secret
# orders-db, refresh every 15 minutes. Rotating the password in Vault
# updates the Secret; mounted files follow; env vars do NOT (Reloader or a
# rollout is needed for those).
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: orders-db
namespace: shop
spec:
refreshPolicy: Periodic
refreshInterval: 15m
secretStoreRef:
name: vault
kind: SecretStore
target:
name: orders-db # the Kubernetes Secret ESO creates and owns
creationPolicy: Owner # deleting the ExternalSecret deletes the Secret
deletionPolicy: Retain # keep the Secret if the provider entry disappears
template:
type: Opaque
data:
# ESO templates use Go text/template syntax
database-url: "postgres://{{ .username }}:{{ .password }}@orders-db-rw.shop.svc:5432/orders?sslmode=require"
username: "{{ .username }}"
password: "{{ .password }}"
data:
- secretKey: username
remoteRef:
key: shop/orders-db # secret/data/shop/orders-db in Vault KV v2
property: username
- secretKey: password
remoteRef:
key: shop/orders-db
property: password
---
# 4) Laravel: one ExternalSecret produces the whole set of .env-style keys
# that the Deployment loads with envFrom (see laravel-app/k8s/).
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: shop-web-env
namespace: shop
spec:
refreshInterval: 1h
secretStoreRef:
name: aws-secretsmanager
kind: ClusterSecretStore
target:
name: shop-web-env
dataFrom:
- extract:
key: prod/shop-web/env # JSON object {"APP_KEY": "...", "DB_PASSWORD": "...", ...}# Secrets Store CSI Driver: secrets are fetched at Pod start by a CSI node
# plugin (DaemonSet) and its provider (here: Vault) and mounted as tmpfs files.
# No Kubernetes Secret exists unless you ask for one with secretObjects.
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
name: orders-vault
namespace: shop
spec:
provider: vault
parameters:
roleName: "orders-api" # Vault role for the Pod's ServiceAccount
vaultAddress: "https://vault.acme.internal:8200"
objects: |
- objectName: "db-username" # becomes the file name
secretPath: "database/creds/orders" # dynamic DB credentials engine
secretKey: "username"
- objectName: "db-password"
secretPath: "database/creds/orders"
secretKey: "password"
# Optional: also mirror into a Kubernetes Secret (needed only for env vars;
# the Secret exists only while some Pod mounts this volume).
secretObjects:
- secretName: orders-db-csi
type: Opaque
data:
- objectName: db-password
key: password
---
apiVersion: v1
kind: Pod
metadata:
name: orders-api-csi-demo
namespace: shop
spec:
serviceAccountName: orders-api
containers:
- name: app
image: ghcr.io/acme/orders-api@sha256:0000000000000000000000000000000000000000000000000000000000000000
volumeMounts:
- name: vault-secrets
mountPath: /mnt/secrets
readOnly: true
volumes:
- name: vault-secrets
csi:
driver: secrets-store.csi.k8s.io
readOnly: true
volumeAttributes:
secretProviderClass: orders-vault# GitOps secrets, two tools. Both keep ciphertext in Git and plain text out of it.
#
# A) Sealed Secrets. kubeseal encrypts with the controller's PUBLIC key; only
# the controller (private key in kube-system) can decrypt, and it writes a
# normal Secret. Default scope "strict": name and namespace are part of the
# ciphertext, so renaming or moving the SealedSecret breaks decryption.
# kubectl create secret generic orders-db -n shop \
# --from-literal=password=change-me --dry-run=client -o yaml \
# | kubeseal --format yaml > orders-db.sealed.yaml
apiVersion: bitnami.com/v1alpha1
kind: SealedSecret
metadata:
name: orders-db
namespace: shop
spec:
encryptedData:
password: AgBy3i4OJSWK+PiTySYZZA9rO43cGDEq... # ciphertext (truncated)
template:
type: Opaque
metadata:
labels:
app.kubernetes.io/name: orders-api
# B) SOPS encrypts the VALUES of a normal Secret manifest (keys stay readable,
# so diffs are reviewable) with age, PGP or a cloud KMS; Flux decrypts
# natively, Argo CD needs a plugin (e.g. helm-secrets or KSOPS).
# The rules live in .sops.yaml at the repository root (see sops.yaml).# .sops.yaml at the root of the GitOps repository.
# `sops encrypt --in-place clusters/prod/orders-db.secret.yaml` picks the first
# rule whose path_regex matches; encrypted_regex limits encryption to the
# Secret's data/stringData so metadata stays readable for kustomize and review.
creation_rules:
- path_regex: clusters/prod/.*\.secret\.yaml$
encrypted_regex: ^(data|stringData)$
kms: arn:aws:kms:eu-central-1:123456789012:key/00000000-0000-0000-0000-000000000000
age: age1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs3290gq # break-glass key (placeholder)
- path_regex: clusters/staging/.*\.secret\.yaml$
encrypted_regex: ^(data|stringData)$
age: age1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs3290gqStorage: classes, claims (including a local PV), a StatefulSet with volumeClaimTemplates and a PDB, snapshots, and a CloudNativePG cluster with backups to object storage:
# StorageClasses for an EKS cluster with the AWS EBS CSI driver.
# provisioner = the CSI driver name; parameters are passed to CreateVolume.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: gp3
annotations:
storageclass.kubernetes.io/is-default-class: "true" # used when a PVC names no class
provisioner: ebs.csi.aws.com
parameters:
type: gp3 # the driver's default type as well
encrypted: "true" # EBS-native encryption (default KMS key unless kmsKeyId)
csi.storage.k8s.io/fstype: ext4
reclaimPolicy: Delete # the default: deleting the PVC deletes the EBS volume
allowVolumeExpansion: true # lets users grow a PVC by editing spec.resources.requests
volumeBindingMode: WaitForFirstConsumer # create the disk in the zone the Pod is scheduled to
---
# For databases: same disks, but Retain, so a deleted PVC never deletes data.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: gp3-retain
provisioner: ebs.csi.aws.com
parameters:
type: gp3
iops: "6000"
throughput: "250" # MiB/s, gp3 only
encrypted: "true"
reclaimPolicy: Retain
allowVolumeExpansion: true
volumeBindingMode: WaitForFirstConsumer
---
# Local NVMe disks: no dynamic provisioning for `local`; PVs are created by
# an admin or by sig-storage-local-static-provisioner. WaitForFirstConsumer is
# what lets the scheduler pick the node that owns the disk.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: local-nvme
provisioner: kubernetes.io/no-provisioner
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer# PersistentVolumeClaims: what an application asks for.
# Access modes are about NODES (RWO, ROX, RWX) or one POD (RWOP), and they
# are matching rules, not write protection.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: reports-data
namespace: shop
spec:
storageClassName: gp3
accessModes: [ReadWriteOncePod] # exactly one Pod in the whole cluster (CSI only)
resources:
requests:
storage: 20Gi # raise later (allowVolumeExpansion) to grow; never shrink
---
# The first consumer: with WaitForFirstConsumer the PVC above stays Pending
# (and no disk exists) until a Pod that uses it is scheduled.
apiVersion: v1
kind: Pod
metadata:
name: reports-writer
namespace: shop
spec:
securityContext:
runAsNonRoot: true
runAsUser: 65532
fsGroup: 65532
containers:
- name: writer
image: busybox:1.37
command: ["sh", "-c", "date >> /data/started.txt && sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: reports-data
---
# Shared files across nodes need a file system that supports ReadWriteMany
# (EFS, Filestore, Azure Files, CephFS, NFS). EBS and PD block disks do not
# (except special multi-attach block modes that need application fencing).
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: shared-exports
namespace: shop
spec:
storageClassName: efs-sc # an EFS CSI StorageClass (not shown)
accessModes: [ReadWriteMany]
resources:
requests:
storage: 5Gi # EFS is elastic; the number is required but not enforced
---
# A statically created local PV: the node affinity pins every consumer to the
# node that holds the disk. If that node dies, the data is unreachable.
apiVersion: v1
kind: PersistentVolume
metadata:
name: local-pv-node-a-nvme0
spec:
capacity:
storage: 800Gi
volumeMode: Filesystem
accessModes: [ReadWriteOnce]
persistentVolumeReclaimPolicy: Retain
storageClassName: local-nvme
local:
path: /mnt/disks/nvme0
nodeAffinity:
required:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values: [node-a]# A StatefulSet with per-replica storage: three INDEPENDENT Redis cache
# shards (no replication between them). Clients pick a shard by key (consistent
# hashing over cache-0/1/2.cache.shop.svc); losing a shard loses only its keys.
# For replicated Redis (sessions, queues) use a Redis operator or Sentinel.
# volumeClaimTemplates -> one PVC per Pod, named <template>-<statefulset>-<ordinal>:
# data-cache-0, data-cache-1, data-cache-2. Each Pod gets ITS claim back
# after a reschedule. Scaling down or deleting keeps the PVCs unless the
# retention policy says otherwise.
apiVersion: v1
kind: Service
metadata:
name: cache
namespace: shop
spec:
clusterIP: None # headless: per-shard DNS cache-0.cache.shop.svc, ...
selector: { app: cache }
ports: [{ name: redis, port: 6379 }]
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: cache
namespace: shop
spec:
serviceName: cache
replicas: 3
selector:
matchLabels: { app: cache }
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain # deleting the StatefulSet keeps the data (default)
whenScaled: Delete # 3 -> 2 deletes data-cache-2 (that shard's keys) after its Pod is gone
template:
metadata:
labels: { app: cache }
spec:
terminationGracePeriodSeconds: 60
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector: { matchLabels: { app: cache } }
containers:
- name: redis
image: redis:8.2
args: ["--appendonly", "yes", "--dir", "/data"]
ports: [{ name: redis, containerPort: 6379 }]
volumeMounts:
- name: data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: data
spec:
storageClassName: gp3-retain
accessModes: [ReadWriteOnce]
resources:
requests:
storage: 10Gi
---
# PodDisruptionBudget: a node drain may evict at most one replica at a time.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: cache
namespace: shop
spec:
maxUnavailable: 1
selector:
matchLabels: { app: cache }# Volume snapshots: CRDs + snapshot controller installed by the distribution,
# csi-snapshotter sidecar next to a CSI driver that supports snapshots.
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshotClass
metadata:
name: ebs-snapclass
driver: ebs.csi.aws.com
deletionPolicy: Retain # keep the cloud snapshot if the VolumeSnapshot is deleted
---
# Take a snapshot of a PVC (crash-consistent unless the app is quiesced first).
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
name: reports-data-2026-11-29
namespace: shop
spec:
volumeSnapshotClassName: ebs-snapclass
source:
persistentVolumeClaimName: reports-data
---
# Restore = a NEW PVC whose dataSource is the snapshot.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: reports-data-restored
namespace: shop
spec:
storageClassName: gp3
dataSource:
name: reports-data-2026-11-29
kind: VolumeSnapshot
apiGroup: snapshot.storage.k8s.io
accessModes: [ReadWriteOnce]
resources:
requests:
storage: 40Gi # >= the source's size at snapshot time (40Gi after the lab's expansion)# PostgreSQL on Kubernetes with the CloudNativePG operator.
# The operator (not a StatefulSet) owns the Pods and PVCs, streaming
# replication, failover, the -rw/-ro/-r Services, PDBs and backups.
#
# Object store for base backups and the WAL archive (Barman Cloud plugin).
apiVersion: barmancloud.cnpg.io/v1
kind: ObjectStore
metadata:
name: orders-backups
namespace: shop
spec:
retentionPolicy: "30d" # recovery window
configuration:
destinationPath: s3://acme-pg-backups/orders/
s3Credentials:
inheritFromIAMRole: true # IRSA: role from the Cluster's ServiceAccount, no static keys
wal:
compression: gzip
---
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: orders-db
namespace: shop
spec:
instances: 3 # 1 primary + 2 hot standbys
serviceAccountTemplate: # IRSA: the instances' ServiceAccount assumes the S3 role
metadata:
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/orders-db-backup
storage:
storageClass: gp3-retain # or local NVMe PVs: replication, not the disk, gives HA
size: 50Gi
walStorage: # separate volume for WAL (cannot be removed later)
storageClass: gp3-retain
size: 10Gi
affinity:
enablePodAntiAffinity: true
topologyKey: topology.kubernetes.io/zone # one instance per zone
podAntiAffinityType: required
enablePDB: true # operator-managed PodDisruptionBudgets (the default)
plugins:
- name: barman-cloud.cloudnative-pg.io
isWALArchiver: true
parameters:
barmanObjectName: orders-backups
bootstrap:
initdb:
database: orders
owner: orders # the operator writes Secret orders-db-app (basic-auth + uri)
---
apiVersion: postgresql.cnpg.io/v1
kind: ScheduledBackup
metadata:
name: orders-db-nightly
namespace: shop
spec:
schedule: "0 0 2 * * *" # six fields: seconds first -> 02:00:00 daily
backupOwnerReference: self
cluster:
name: orders-db
method: plugin
pluginConfiguration:
name: barman-cloud.cloudnative-pg.io
# The application connects to the Service orders-db-rw (always the primary)
# with credentials from Secret orders-db-app (keys: username, password, host,
# port, dbname, uri, jdbc-uri, ...), e.g.
# env:
# - name: DATABASE_URL
# valueFrom: { secretKeyRef: { name: orders-db-app, key: uri } }The Go angle
- Two tiers of config, on purpose.
LoadStaticfails fast at start (a missing Secret should stop a rollout, not let a broken Pod pass readiness);ReadDirplusWatcherhandles what may change live. Deciding which setting belongs in which tier is the design decision; the code is small. - Watch the directory, not the file. fsnotify's README: "Watch the parent directory and use Event.Name to filter out files you're not interested in." The watcher goes further and does not filter at all: event names during a kubelet update are implementation details (
..data_tmp, the timestamped directory, the per-key links), and they differ between Linux inotify and macOS kqueue. On the host run in the Lab, one swap produced 13 events on macOS. Debounce, re-read, compare bytes. - Atomic swap for readers.
atomic.Pointer[T](Go 1.19) gives lock-free reads of an immutable config value; never mutate the struct a reader may hold.slog.LevelVar(Go 1.21,log/slog) is the standard library's built-in hot-reloadable log level. - Validate before apply. A ConfigMap edit reaches every replica within about a minute. If a bad value crashes the process, every replica crash-loops together. Keep the last good config and log loudly (the watcher calls
OnError, which is where a metric belongs). - inotify limits. Each watcher consumes an inotify instance and watches; fsnotify documents
fs.inotify.max_user_watchesandfs.inotify.max_user_instancesand notes that defaults differ per distro. One directory watch per process is cheap; one watch per file in a big tree is not. - Secrets on use, not at init.
SecretFile.Valuere-reads after a TTL.sql.Open(driver, dsn)keeps the DSN it was given, soSetConnMaxLifetimealone would re-dial with the old password. Thedbconn.Connectorbelow implementsdriver.Connector, whoseConnectruns for every new physical connection and re-reads the DSN from theSecretFile;SetConnMaxLifetimethen bounds how long pre-rotation connections live. The database must accept both passwords for that window (or use dynamic credentials from Vault with leases). - Downward API for runtime tuning.
resourceFieldRef: limits.memoryexported asGOMEMLIMITmakes the garbage collector respect the container limit: the GC guide says Go 1.19 "added support for setting a runtime memory limit", and the runtime docs: "GOMEMLIMIT is a numeric value in bytes with an optional unit suffix", which is what the downward API produces. - viper preview. spf13/viper wraps fsnotify for config files:
// Viper (not used in this module): watches one config file it loaded.
viper.SetConfigFile("/etc/orders/config/app.yaml")
_ = viper.ReadInConfig()
viper.OnConfigChange(func(e fsnotify.Event) { log.Println("config changed:", e.Name) })
viper.WatchConfig() // "All config paths must be defined prior to calling WatchConfig()"It merges flags, env, files and remote stores, which is convenient; check how the version you use handles the kubelet's ..data swap before relying on WatchConfig for a mounted ConfigMap, and keep validation in your code either way. Environment-variable and flag handling in plain Go is in CLI Flags, Environment Variables & Logging.
Laravel
Before
The setup many Laravel teams start with on Kubernetes: the whole .env file in a ConfigMap mounted with subPath (secrets in a ConfigMap, never updated), config cached at image build time, and a ReadWriteMany volume for uploads.
# Before: four problems in one Deployment
apiVersion: apps/v1
kind: Deployment
metadata: { name: shop-web }
spec:
replicas: 3
selector: { matchLabels: { app: shop-web } }
template:
metadata: { labels: { app: shop-web } }
spec:
containers:
- name: app
image: ghcr.io/acme/shop-web:latest # image ran `php artisan config:cache` at BUILD time
volumeMounts:
- name: dotenv # 1. .env (with APP_KEY, DB_PASSWORD) in a ConfigMap
mountPath: /var/www/html/.env
subPath: .env # 2. subPath: edits never reach the Pod
- name: uploads # 3. user uploads on a shared volume
mountPath: /var/www/html/storage/app/public
volumes:
- name: dotenv
configMap: { name: shop-web-dotenv }
- name: uploads
persistentVolumeClaim: { claimName: shop-uploads } # 4. RWX NFS: slow, single point of failureAfter
Plain settings in a ConfigMap, secrets in a Secret written by ESO (the shop-web-env ExternalSecret above), both loaded with envFrom; config cached at Pod start; emptyDir only for framework scratch; uploads on S3.
# Non-secret Laravel settings as environment variables. Laravel reads real
# environment variables before (and instead of) a .env file, so no .env file
# exists in the image or the Pod: this ConfigMap plus the shop-web-env Secret
# (written by External Secrets Operator) ARE the .env.
apiVersion: v1
kind: ConfigMap
metadata:
name: shop-web-config
namespace: shop
data:
APP_ENV: production
APP_DEBUG: "false"
APP_URL: https://shop.example.com
LOG_CHANNEL: stderr # the container runtime collects stdout/stderr
DB_CONNECTION: pgsql
DB_HOST: orders-db-rw.shop.svc # CloudNativePG read-write Service
DB_PORT: "5432"
DB_DATABASE: orders # database created by the CloudNativePG cluster orders-db
CACHE_STORE: redis
SESSION_DRIVER: redis # sessions must not live in a Pod's filesystem
QUEUE_CONNECTION: redis
REDIS_HOST: sessions-redis.shop.svc # replicated Redis from a Redis operator (not the cache shards)
FILESYSTEM_DISK: s3 # uploads go to object storage, not a volume
AWS_DEFAULT_REGION: eu-central-1
AWS_BUCKET: acme-shop-uploads
AWS_USE_PATH_STYLE_ENDPOINT: "false"# Laravel web tier on Kubernetes: php-fpm + Nginx in one Pod.
# Config: envFrom a ConfigMap (plain settings) and a Secret (APP_KEY,
# DB_PASSWORD, ...). The entrypoint runs `php artisan config:cache` at
# START, inside the Pod, where the real environment exists, so the cached
# config matches this Pod's env. A changed Secret therefore needs a new Pod
# (Reloader annotation below), never an in-place edit.
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-web
namespace: shop
annotations:
reloader.stakater.com/auto: "true"
spec:
replicas: 3
selector:
matchLabels: { app: shop-web }
template:
metadata:
labels: { app: shop-web }
spec:
serviceAccountName: shop-web # IRSA/Workload Identity for S3: no AWS keys in env
securityContext:
runAsNonRoot: true
runAsUser: 33 # www-data in the Debian php:*-fpm images (82 on -alpine)
fsGroup: 33
containers:
- name: app
image: ghcr.io/acme/shop-web@sha256:1111111111111111111111111111111111111111111111111111111111111111
envFrom:
- configMapRef: { name: shop-web-config }
- secretRef: { name: shop-web-env } # APP_KEY, DB_USERNAME, DB_PASSWORD, ...
env:
- name: DB_PASSWORD_FILE # optional file-based alternative
value: /run/secrets/db/password
volumeMounts:
- { name: framework, mountPath: /var/www/html/storage/framework }
- { name: bootstrap-cache, mountPath: /var/www/html/bootstrap/cache }
- { name: logs, mountPath: /var/www/html/storage/logs }
- { name: db-password, mountPath: /run/secrets/db, readOnly: true }
readinessProbe:
tcpSocket: { port: 9000 }
- name: web
image: ghcr.io/acme/shop-web-nginx@sha256:2222222222222222222222222222222222222222222222222222222222222222
ports: [{ name: http, containerPort: 8080 }]
readinessProbe:
httpGet: { path: /up, port: http } # Laravel's health route
volumes:
# Writable scratch that Laravel needs; per Pod, gone with the Pod.
- { name: framework, emptyDir: {} } # compiled views, cache files, sessions (if file driver)
- { name: bootstrap-cache, emptyDir: {} } # config.php / routes cache written at start
- { name: logs, emptyDir: { sizeLimit: 100Mi } }
- name: db-password
secret:
secretName: orders-db-app # written by CloudNativePG
items: [{ key: password, path: password }]
# NOT here: a PVC for storage/app/public. With replicas on several nodes
# it would need ReadWriteMany, and uploads would still be invisible to
# the CDN and to queue workers on other nodes. Use the s3 disk instead.The entrypoint caches config where the real environment exists, then execs php-fpm:
#!/bin/sh
# Container entrypoint for the Laravel app image on Kubernetes.
# Runs at Pod start, when envFrom (ConfigMap + Secret) is already present.
set -eu
# Fail fast if the Secret was not mounted: a Pod that starts without APP_KEY
# would serve 500s; a Pod that exits is held back by the rollout instead.
: "${APP_KEY:?APP_KEY missing: is Secret shop-web-env referenced in envFrom?}"
# Cache config from THIS Pod's environment. After this, env() outside config/
# returns only real environment variables and .env is never read.
php artisan config:cache
php artisan route:cache
php artisan view:cache
# exec: php-fpm becomes PID 1 and receives SIGTERM from the kubelet.
exec docker-php-entrypoint "$@"config/database.php with the *_FILE convention for the password, and config/filesystems.php with the S3 disk:
<?php
// config/database.php (excerpt): the pgsql connection on Kubernetes.
// Every value comes from env() here, inside config/, which is the only place
// env() keeps working after `php artisan config:cache`.
$secretFile = static function (string $var, string $fallback = ''): string {
// *_FILE convention: read a mounted Secret file if the variable is set.
// The value is read once, when config is cached at Pod start; a rotated
// password therefore reaches Laravel on the next Pod, not mid-flight.
$path = env($var . '_FILE');
if (is_string($path) && $path !== '' && is_readable($path)) {
return trim((string) file_get_contents($path));
}
return (string) env($var, $fallback);
};
return [
'default' => env('DB_CONNECTION', 'pgsql'),
'connections' => [
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'laravel'),
'password' => $secretFile('DB_PASSWORD'),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'require'),
],
],
];<?php
// config/filesystems.php (excerpt): uploads on Kubernetes go to S3 (or any
// S3-compatible store), not to a volume. Requires
// composer require league/flysystem-aws-s3-v3 "^3.0" --with-all-dependencies
// On EKS with IRSA / Pod Identity, leave AWS_ACCESS_KEY_ID unset: the AWS SDK
// picks up the Pod's web-identity credentials automatically.
return [
'default' => env('FILESYSTEM_DISK', 'local'),
'disks' => [
// Pod-local and ephemeral on Kubernetes (emptyDir or the container layer):
// fine for temporary files, wrong for anything a user uploaded.
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
],
],
];The Laravel angle
- Laravel .env from Secret: no file needed. "Any variable in your .env file can be overridden by external environment variables such as server-level or system-level environment variables." On Kubernetes the ConfigMap and Secret loaded with
envFromare the environment, so the image ships no.envat all and one image serves every environment. - config:cache freezes env(). The docs: "Once the configuration has been cached, your application's .env file will not be loaded by the framework during requests or Artisan commands; therefore, the env function will only return external, system level environment variables." Two consequences on Kubernetes: (1) run
config:cacheat container start (entrypoint) or in an init step of the same Pod, never in the Dockerfile, where the build machine's environment would be baked in; (2) a changed Secret reaches Laravel only through a new Pod, so add Reloader or a checksum annotation. Callenv()only insideconfig/; the docs say "you should ensure you are only calling the env function from within your application's configuration (config) files." - Queue workers and the scheduler use the same
envFromand the same entrypoint; aqueue:workprocess keeps its booted config until it exits, so roll workers together with the web tier (php artisan queue:restartis the non-Kubernetes equivalent). - Storage volume vs S3.
storage/framework(compiled views, file cache, file sessions) andbootstrap/cacheare per-Pod scratch:emptyDir. User uploads are shared state: thes3disk ("The s3 driver is used to write to Amazon's S3 cloud storage service"), installed withleague/flysystem-aws-s3-v3, credentials from IRSA or Workload Identity rather thanAWS_ACCESS_KEY_IDin a Secret.php artisan storage:linkand thepublicdisk only make sense for a single server. The Go side of uploads is File Uploads, S3 & CDN. - Sessions and cache go to Redis (
SESSION_DRIVER=redis,CACHE_STORE=redis); with the file driver a user's session lives in one Pod'semptyDirand disappears on the next deploy or on a different replica. - Laravel's encrypted env files (
php artisan env:encrypt,.env.encrypted) are an alternative to SOPS for a single app: the docs say the decryption key "should be stored in a secure password manager", which on Kubernetes means a Secret again. ESO or SOPS keeps one mechanism for every app in the cluster. - Octane workers keep the application booted between requests, so config is as frozen as with
config:cacheuntil the worker restarts; treat a config change as a rollout.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| Config change does not reach the app | Pick a reload path per value | Mounted files + app watch, or Reloader / checksum annotation | Every value has a known update time | App code, or a controller |
| Secrets readable in Git | Encrypt or externalise | Sealed Secrets, SOPS, or ESO from Vault/cloud | Git stays reviewable and safe | Key management |
| etcd backup leaks credentials | Encryption at rest | EncryptionConfiguration with KMS v2, rewrite Secrets | Backups and disks hold ciphertext | KMS plugin, key policy |
| Developers can read prod Secrets | Namespace and RBAC design | No list/watch, no Pod create in prod namespaces for humans | Least privilege | Break-glass process |
| Password rotation needs downtime | File-based secrets + dual credentials | ESO refresh, SecretFile TTL, DB accepts old and new for a window | Zero-downtime rotation | DB-side procedure |
| Rollout deadlocks on an RWO volume | Recreate or StatefulSet | strategy: Recreate, or per-replica PVCs | No Multi-Attach | Short downtime for single-instance apps |
| Pod unschedulable after provisioning | Topology-aware binding | WaitForFirstConsumer classes | Disk created where the Pod runs | First Pod start slightly slower |
| PVC deleted by accident | Retain + snapshots + backups | reclaimPolicy: Retain, VolumeSnapshots, DB backups off-cluster | Data survives mistakes | Manual cleanup of Released PVs |
| Volume full | Expansion | allowVolumeExpansion, patch the PVC, alert at 80 % | Online growth | Cloud modify limits; no shrink |
| Uploads lost or inconsistent across replicas | Object storage | Laravel s3 disk, Go S3 client, CDN in front | Stateless web tier | Egress, eventual listing semantics |
| Database HA on Kubernetes | Operator | CloudNativePG / Percona / Zalando with PDBs, zone spread, WAL archive | Automated failover and backups | Operator expertise |
Rotating a database password without downtime
1 create the new password in Vault as a second user or second password (DB accepts old + new)
2 ESO refresh (or force: kubectl annotate externalsecret orders-db force-sync=$(date +%s) --overwrite)
3 Secret orders-db changes -> kubelet swaps /etc/orders/secrets/database-url within about a minute
4 Go: dbconn.Connector re-reads the SecretFile on every new connection (after its TTL) -> new connections
use the new password; SetConnMaxLifetime retires the pre-rotation ones
Laravel (env-based): Reloader rolls shop-web; new Pods cache config with the new password
5 after every replica uses the new credential (check DB login stats), revoke the old oneWith Vault's database secrets engine and the CSI driver or ESO, step 1 disappears: each Pod or each refresh gets its own short-lived user.
Rolling out a config change safely
Version the ConfigMap (orders-config-v8, or Kustomize's hash suffix), mark it immutable, and change the Pod template to point at it: the change is now an ordinary Deployment rollout with maxUnavailable, readiness gates and kubectl rollout undo. Keep the previous ConfigMap until the rollout is complete so rollback works. For live-reloadable flags, edit the mutable ConfigMap and watch the config reloaded log line (or a metric) on every replica.
Secrets in a GitOps repository
Choose one mechanism per cluster: ESO ExternalSecret manifests (no secret material in Git at all), SOPS-encrypted Secret manifests decrypted by Flux, or SealedSecrets. Commit only those; block plain kind: Secret with a policy (Kyverno or Gatekeeper rule, or a CI check) and with secret scanning on the repository (Secure SDLC).
Moving uploads off a shared volume
Switch the Laravel default disk to s3, copy existing files (aws s3 sync from a Pod that mounts the old PVC), serve public files through the bucket's CDN URL, then remove the PVC from the Deployment. Generate temporary URLs for private files instead of streaming them through PHP.
Restoring a database from backup
With CloudNativePG, recovery is a new Cluster whose bootstrap.recovery points at the object store (or a VolumeSnapshot), optionally with a target time for PITR; the old cluster is never overwritten in place. Practise it: a backup you have not restored is a hope, not a backup (Backup, PITR & DR).
Moving a stateful workload to another zone or cluster
A zonal disk cannot follow a Pod across zones. Options: replicate at the application level (add a replica in the new zone, switch over, remove the old one, which is what database operators do); restore a snapshot in the new zone (snapshots are regional for EBS and PD); or back up and restore with Velero for whole namespaces.
Choosing
Which secret delivery
| Situation | Choose | Reason |
|---|---|---|
| Small team, one cluster, GitOps | Sealed Secrets | No external dependency; ciphertext in Git |
| Flux, cloud KMS available, many clusters | SOPS | One KMS key, readable diffs, native Flux support |
| Vault or a cloud secret manager already in use | External Secrets Operator | Store stays the source of truth; rotation by refresh |
| Requirement: no secret material in etcd, per-Pod identity to the store | Secrets Store CSI Driver | Files fetched per Pod, Secret object optional |
| Dynamic, short-lived database credentials | Vault database engine + CSI driver or Vault Agent | Per-Pod users with leases |
| A third-party app that only reads env vars | ESO Secret + secretKeyRef + Reloader | Works, at the cost of restarts on rotation |
Which reload strategy
| Value | Delivery | Reload |
|---|---|---|
| Port, listen address, feature that changes wiring | Env (envFrom) | Rollout via checksum annotation or Reloader |
| Log level, feature flags, timeouts, rate limits | Mounted ConfigMap | Hot reload (watch + validate) |
| TLS certificate and key | Mounted Secret | Re-read on handshake or watch (cert-manager renews) |
| Database password | Mounted Secret (*_FILE) | TTL re-read in Go; Reloader for Laravel |
| Laravel settings | envFrom + config:cache at start | Reloader |
| Large static files (GeoIP, ML model) | Image, init container download, or a volume | New image or Job; not a ConfigMap |
Which storage
| Workload | Storage | Access mode | Class settings |
|---|---|---|---|
| Stateless web/API | None (or emptyDir scratch) | - | - |
| Single-instance app with state (Gitea, a CMS) | Cloud block disk | RWO or RWOP, strategy: Recreate | WaitForFirstConsumer, Retain, expansion |
| Replicated database / broker | Block disk or local NVMe per replica (StatefulSet / operator) | RWO | Retain, zone spread, PDB |
| Shared files many Pods write | Prefer object storage; else EFS / Filestore / Azure Files / CephFS | RWX | Throughput mode, backups |
| Read-mostly dataset for many Pods | ROX disk clone, or bake into image, or object storage | ROX | Snapshot-based clones |
| Big temporary scratch | Generic ephemeral volume or disk-backed emptyDir | RWO | Delete |
Managed database vs in-cluster
| Situation | Choose | Reason |
|---|---|---|
| Cloud-native shop, few databases, no PostgreSQL experts | Managed (RDS, Cloud SQL, Azure) | Provider runs failover, patching, backups |
| On-prem or multi-cloud portability required | In-cluster operator (CloudNativePG, Percona) | Same manifests everywhere |
| Many small databases (per-tenant, per-PR environments) | In-cluster operator | Cheap, fast, declarative |
| Latency-critical, local NVMe, large IOPS at low cost | In-cluster with local PVs | Shared-nothing, replication for durability |
| Strict compliance with provider certifications | Managed | Audit artefacts already exist |
| Team new to Kubernetes | Managed | Learn one hard thing at a time (the CNCF post's advice) |
In architecture: from a single process to a distributed system
Configuration, secrets and storage decide what a Pod depends on besides its image: the more a workload holds in volumes and env, the less freely Kubernetes can move, scale and replace it. The architecture question at every scale is where state and secrets live, and how changes reach running code.
Monolith: one Deployment, one database
A Laravel monolith on one cluster: a shop-web Deployment (web), the same image as shop-worker (queues) and shop-scheduler, one ConfigMap and one Secret loaded with envFrom, config:cache at start, Reloader on all three, uploads on S3, sessions and cache in Redis, and PostgreSQL either managed or as a three-instance CloudNativePG cluster with WAL archiving. No PVC is attached to any PHP Pod; the only persistent volumes in the namespace belong to the database operator and Redis. Encryption at rest is on (managed cluster default or KMS v2), and only the CI deploy identity can write Secrets.
Modular monolith: shared platform, separate config
As the codebase splits into modules with their own processes (a Go PDF renderer, a search indexer), each gets its own ConfigMap and Secret, its own ServiceAccount and Vault role, and RBAC that lets it read only its own objects. Shared settings (the Redis host, the S3 bucket) live in a common ConfigMap referenced by several Deployments; changing it triggers Reloader on all of them, which is a feature (consistency) and a risk (a fleet-wide restart), so shared ConfigMaps should be small and stable.
Microservices: many teams, one secret platform
Twenty services, each in its own namespace, deployed by Argo CD or Flux. The platform team runs ESO with one SecretStore per namespace bound to a Vault role or cloud IAM role per service (never one powerful ClusterSecretStore for all), the CSI driver where per-Pod identity is required, and an admission policy that rejects plain kind: Secret from Git. Each service owns its database: managed instances for the critical ones, CloudNativePG clusters for the rest, all with backups to object storage in another account. StorageClasses are a platform product: gp3 (Delete) for scratch, gp3-retain for data, local-nvme for the database tier, all with WaitForFirstConsumer. Packaging is Helm or Kustomize (Packaging), infrastructure (KMS keys, IAM roles, buckets, Vault mounts) is Terraform, and the pipelines that render and apply manifests run in GitHub Actions or GitLab CI (GitOps).
New service "invoices" onboarding, platform golden path
1 Terraform: Vault role invoices (bound to SA invoices in ns invoices), S3 bucket, KMS key grant
2 GitOps repo: namespace, SecretStore (vault, role invoices), ExternalSecret invoices-db
3 CloudNativePG Cluster invoices-db (3 instances, gp3-retain, ObjectStore in backup account)
4 Deployment: envFrom ConfigMap, DATABASE_URL_FILE from Secret invoices-db-app, Reloader annotation
5 policy check: no plain Secret, no hostPath, PVCs only with approved StorageClassesDistributed data: zones, regions and disaster recovery
Block volumes are zonal, so a StatefulSet replica is pinned to the zone of its disk; durability across zones comes from application replication (PostgreSQL streaming replication, Kafka ISR, RabbitMQ quorum queues), not from the disk. CloudNativePG recommends spreading instances over availability zones and relying on PostgreSQL replication rather than storage-level replication; across regions it offers replica clusters (a standby cluster that follows the primary through the WAL archive or streaming), with promotion as an explicit, declarative action. Secrets must be available in every region before the workloads are: a replicated Vault or the cloud secret manager's multi-region replication, plus ESO in each cluster. Object storage holds the backups and the uploads, ideally in another account and region with versioning and object lock ("Enable object locking to prevent objects from being deleted or overwritten", per the Barman Cloud plugin docs). Volume snapshots are not a cross-region DR plan unless they are copied.
Scaling path: 1x, 10x, 100x
| Scale | Config and secrets | Storage | Databases |
|---|---|---|---|
| 1x (one team, one cluster) | ConfigMap + Secret per app, Sealed Secrets or SOPS, Reloader, managed encryption at rest | Default StorageClass (WaitForFirstConsumer), Retain class for data | Managed database, or one CloudNativePG cluster |
| 10x (several teams, a few clusters) | ESO per namespace from Vault or the cloud store, policies against plain Secrets, immutable versioned ConfigMaps | Platform-owned classes, snapshots, expansion alerts, quotas on requests.storage | Operator per engine, PDBs, WAL archive, restore drills |
| 100x (many clusters, regions) | Multi-region secret stores, KMS per cluster, CSI driver for per-Pod identity, audit of every Secret read | Local NVMe tiers, VolumeAttributesClass for performance changes, Velero for namespace backups | Replica clusters across regions, fleet-wide operator upgrades, managed for the crown jewels |
Lab
Label: every kubectl, kubeseal, sops, helm and etcdctl command below is expected, not run: no Kubernetes cluster may be started in this build environment (AUTHORING cost rule). Their output is shown as the shape the documentation describes, with placeholders (<...>) where values would be cluster-specific; no output was invented. Steps marked ran on the host were executed on macOS (Go 1.27.4, darwin/arm64) and show real output, saved in pipeline/sources/kubernetes-config-secrets-storage/lab-host-output.txt.
1. Test the config package (ran on the host)
cd docs/snippets/platform/kubernetes-config-secrets-storage/go-service
gofmt -l . ; go vet ./... ; go test -race -count=1 ./...
# ok academy/kubernetes-config-secrets-storage 1.387s
# ok academy/kubernetes-config-secrets-storage/config 1.776s2. Hot reload against a kubelet-style atomic swap (ran on the host)
project.sh performs the same steps as the kubelet's atomic writer; the service watches the directory.
LAB=<an empty scratch directory>
go build -o "$LAB/orders-api" . && cp scripts/project.sh "$LAB/" && cd "$LAB"
./project.sh config log_level=info request_timeout=5s features=checkout_v2=false
./project.sh secrets database-url=postgres://app:pw@orders-db-rw:5432/app
PORT=18081 CONFIG_DIR=config DATABASE_URL_FILE=secrets/database-url ./orders-api > log.txt 2>&1 &
ls -l config | awk 'NR>1{print $9, $10, $11}'
# features -> ..data/features
# log_level -> ..data/log_level
# request_timeout -> ..data/request_timeout
curl -s localhost:18081/config
# {"features":[],"log_level":"info","request_timeout":"5s"}
./project.sh config log_level=debug request_timeout=2s features=checkout_v2=true
curl -s localhost:18081/config
# {"features":["checkout_v2"],"log_level":"debug","request_timeout":"2s"}
./project.sh config log_level=loud request_timeout=2s features=checkout_v2=true # invalid
curl -s localhost:18081/config
# {"features":["checkout_v2"],"log_level":"debug","request_timeout":"2s"} (last good kept)Service log (time field removed; the 13 DEBUG config dir event lines that macOS kqueue produced during the rejected update are counted, not shown):
{"level":"INFO","msg":"listening","addr":":18081","config_dir":"config"}
{"level":"INFO","msg":"config reloaded","log_level":"debug","request_timeout":"2s","features":["checkout_v2"]}
{"level":"ERROR","msg":"config reload rejected, keeping previous config","err":"log_level \"loud\": want debug, info, warn or error"}3. base64 is not encryption (ran on the host)
printf change-me | base64 # Y2hhbmdlLW1l
echo Y2hhbmdlLW1l | base64 -d # change-mePrerequisites for steps 4-9 (expected, not run)
A cluster with a default CSI StorageClass (steps 7-8: the AWS EBS CSI driver for the ebs.csi.aws.com classes), the snapshot CRDs and controller, Reloader, and for step 8 the CloudNativePG operator with the Barman Cloud plugin. Then: kubectl create namespace shop; build this chapter's go-service into an image the way Images & Dockerfiles builds its service (distroless static, non-root) and replace the all-zero @sha256: placeholder in k8s/deployment-orders-api.yaml with that digest (or drop imagePullSecrets and use a local image in kind); replace change-me and the Vault/AWS/S3 names with real ones, or skip the files that need them (external-secrets.yaml, secretproviderclass.yaml, cnpg-cluster.yaml). The image has no shell, so the steps observe it through port-forward, logs and an ephemeral debug container.
4. ConfigMap as env vs files (expected, not run)
The Deployment's Reloader annotation names only orders-env (configmap.reloader.stakater.com/reload: "orders-env"), so editing the file-mounted orders-config does not replace Pods and the hot reload can be observed. The env check uses OTEL_SERVICE_NAME, a key nothing else depends on (changing PORT would break the fixed containerPort and probes).
kubectl apply -f k8s/rbac-secrets.yaml -f k8s/configmap.yaml -f k8s/secret.yaml -f k8s/deployment-orders-api.yaml
kubectl -n shop rollout status deploy/orders-api
POD=$(kubectl -n shop get pod -l app.kubernetes.io/name=orders-api -o name | head -1)
kubectl -n shop port-forward $POD 18080:8080 &
curl -s localhost:18080/config # {"features":["gift_cards"],"log_level":"info","request_timeout":"5s"}
kubectl -n shop patch configmap orders-config --type merge -p '{"data":{"log_level":"debug"}}'
# within about a minute (kubelet sync period + cache delay), same Pod, no restart:
curl -s localhost:18080/config # ..."log_level":"debug"...
kubectl -n shop logs $POD | grep 'config reloaded'
# env and subPath need a look inside the container: attach a debug container to its process namespace
kubectl -n shop debug -it ${POD#pod/} --image=busybox:1.37 --target=orders-api -- sh
# tr '\0' '\n' < /proc/1/environ | grep ^OTEL_SERVICE_NAME= -> OTEL_SERVICE_NAME=orders-api
# cat /proc/1/root/etc/nginx/conf.d/tuning.conf -> old content forever (subPath)
kubectl -n shop patch configmap orders-env --type merge -p '{"data":{"OTEL_SERVICE_NAME":"orders-api-v2"}}'
# Reloader sees orders-env change and rolls the Deployment: the OLD Pods keep orders-api in
# /proc/1/environ until they are replaced; the NEW Pods start with orders-api-v2
kubectl -n shop rollout status deploy/orders-api5. Who can read Secrets (expected, not run)
kubectl auth can-i get secret/orders-db -n shop --as=system:serviceaccount:shop:orders-api # no (it only mounts)
kubectl auth can-i get secret/orders-db -n shop --as=system:serviceaccount:shop:orders-db-rotator # yes
kubectl auth can-i list secrets -n shop --as=system:serviceaccount:shop:orders-db-rotator # no
kubectl auth can-i create pods -n shop --as=dev@acme.example # if yes: can read every Secret here6. Encryption at rest check (expected, not run; self-managed control plane)
ETCDCTL_API=3 etcdctl --cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key \
get /registry/secrets/shop/orders-db | hexdump -C | head
# without encryption: readable "change-me" in the dump
# with KMS v2: the value starts with k8s:enc:kms:v2:<provider name>:
kubectl get secrets --all-namespaces -o json | kubectl replace -f - # after enabling, rewrite all7. Storage: WaitForFirstConsumer, expansion, snapshot (expected, not run)
kubectl apply -f k8s/storageclass.yaml
kubectl apply -f k8s/pvc.yaml # the claims plus Pod reports-writer, the first consumer of reports-data
kubectl -n shop get pvc reports-data # right away: Pending, no VOLUME (WaitForFirstConsumer)
# NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
# reports-data Pending gp3 <age>
# once the scheduler has placed reports-writer, the provisioner creates the disk in that zone:
kubectl -n shop wait pvc/reports-data --for=jsonpath='{.status.phase}'=Bound --timeout=5m
kubectl -n shop get pvc reports-data # Bound, VOLUME pvc-<uid>, CAPACITY 20Gi, in reports-writer's zone
kubectl -n shop patch pvc reports-data -p '{"spec":{"resources":{"requests":{"storage":"40Gi"}}}}'
kubectl -n shop get pvc reports-data -o jsonpath='{.status.capacity.storage}' # 40Gi once resized
kubectl apply -f k8s/volumesnapshot.yaml # snapshot of the 40Gi volume + a 40Gi restore claim
kubectl -n shop get volumesnapshot reports-data-2026-11-29 -o jsonpath='{.status.readyToUse}' # true
# reports-data-restored stays Pending (WaitForFirstConsumer) until a Pod mounts it8. StatefulSet PVCs and a CloudNativePG cluster (expected, not run)
kubectl apply -f k8s/statefulset.yaml
kubectl -n shop get pvc -l app=cache # data-cache-0, data-cache-1, data-cache-2
kubectl -n shop scale statefulset cache --replicas=2
kubectl -n shop get pvc data-cache-2 # gone after the Pod terminates (whenScaled: Delete)
kubectl apply -f k8s/cnpg-cluster.yaml # needs the CloudNativePG operator and the Barman Cloud plugin
kubectl -n shop get cluster orders-db # INSTANCES 3, READY 3, STATUS <healthy>, PRIMARY orders-db-1
kubectl -n shop get pdb # two PDBs created by the operator
kubectl -n shop get secret orders-db-app -o jsonpath='{.data.uri}' | base64 -d
kubectl cnpg backup -n shop orders-db --method=plugin --plugin-name=barman-cloud.cloudnative-pg.io9. Seal and encrypt for Git (expected, not run)
# Sealed Secrets (needs the controller in the cluster)
kubectl create secret generic orders-db -n shop --from-literal=password=change-me \
--dry-run=client -o yaml | kubeseal --format yaml > orders-db.sealed.yaml
# SOPS with a local age key, in a scratch GitOps checkout
age-keygen -o age.key # prints "Public key: age1..."
export SOPS_AGE_KEY_FILE=$PWD/age.key # where sops looks for the private key
RECIPIENT=$(grep -o 'age1[0-9a-z]*' age.key | head -1)
mkdir -p clusters/prod
cat > .sops.yaml <<EOF
creation_rules:
- path_regex: clusters/prod/.*\.secret\.yaml$
encrypted_regex: ^(data|stringData)$
age: $RECIPIENT
EOF
kubectl create secret generic orders-db -n shop --from-literal=password=change-me \
--dry-run=client -o yaml > clusters/prod/orders-db.secret.yaml
sops encrypt --in-place clusters/prod/orders-db.secret.yaml
grep -c 'ENC\[AES256_GCM' clusters/prod/orders-db.secret.yaml # one per encrypted value; metadata readable
sops decrypt clusters/prod/orders-db.secret.yaml | grep password # round trip with the age keyCommon misconceptions
| Belief | Reality |
|---|---|
| Secrets are encrypted | base64-encoded; plain in etcd unless an EncryptionConfiguration with a real first provider is set |
| Editing a ConfigMap updates the app | Env vars never update; mounted files after the kubelet sync period + cache delay; subPath never |
subPath is just a tidier mount | It is a bind mount of one resolved file and "will not receive ConfigMap updates" |
list on Secrets only shows names | List responses carry the data: list/watch = read all Secrets in the namespace |
| No RBAC on Secrets means no access | Anyone who can create Pods (or Deployments, Jobs) in the namespace can mount and read them |
| ESO removes Kubernetes Secrets | ESO writes Kubernetes Secrets; encryption at rest and RBAC still apply |
| Rotating the Sealed Secrets key un-leaks secrets | Leaked secrets must themselves be rotated; old keys are kept so old SealedSecrets still decrypt |
| ReadWriteOnce means one Pod | One node; several Pods on that node can share it; use ReadWriteOncePod for one Pod |
| Access modes enforce read-only | They are matching and attach rules; "Volume access modes do not enforce write protection once the storage has been mounted" |
| Deleting a StatefulSet deletes its data | PVCs are kept by default (Retain); only persistentVolumeClaimRetentionPolicy changes that |
| Deleting a PVC is always safe | With the default Delete reclaim policy, the cloud disk is deleted too |
| A volume snapshot is a backup | Crash-consistent copy in the same storage system; not off-site, not application-consistent |
emptyDir is free scratch space | Counts against node ephemeral storage, or against container memory with medium: Memory |
hostPath is fine for app data | Node-specific, not counted as ephemeral storage, and a container-escape vector |
| A StatefulSet chart is a production database | Failover, backups, PITR, upgrades and drains need an operator or a managed service |
config:cache in the Dockerfile is an optimisation | It bakes the build environment into the image; cache at Pod start instead |
Cheat sheet
| Topic | Remember |
|---|---|
| ConfigMap | Non-secret, ≤ 1 MiB, same namespace; env/configMapKeyRef (one key), envFrom (all keys), volume (files) |
| Update timing | Env: next Pod. Volume: sync period (syncFrequency 1m) + cache delay. subPath: never. Immutable: new name |
| Secret | base64 in data, plain in stringData on write, ≤ 1 MiB, tmpfs on nodes, only sent to nodes that need it |
| Secret types | Opaque, kubernetes.io/tls, kubernetes.io/dockerconfigjson, basic-auth, ssh-auth, service-account-token |
| Encryption at rest | --encryption-provider-config; first provider encrypts; KMS v2 stable 1.29; rewrite all Secrets after changes |
| RBAC | get by resourceNames only; never list/watch; Pod create = Secret read |
| Env vs files | Files for credentials (*_FILE), rotation without restart; env for static settings |
| ESO | SecretStore (how) + ExternalSecret (what), refreshInterval, creationPolicy: Owner |
| Secrets Store CSI | SecretProviderClass, tmpfs mount at Pod start, rotation alpha, secretObjects for env |
| GitOps | Sealed Secrets (controller key pair, strict scope) or SOPS (.sops.yaml, --encrypted-regex) |
| Reload | Checksum annotation (Helm), hash suffix (Kustomize), Reloader (runtime), hot reload (watch the directory) |
| Pod volumes | emptyDir (+sizeLimit), projected (token + config), downwardAPI, avoid hostPath |
| PV / PVC | PVC = request (namespaced), PV = disk (cluster), 1:1 via ClaimRef, Pending until matched |
| StorageClass | provisioner, parameters, reclaimPolicy (default Delete), allowVolumeExpansion, WaitForFirstConsumer |
| Access modes | RWO node, ROX many readers, RWX many writers (file systems), RWOP one Pod (CSI) |
| Expansion / snapshots | Patch PVC size (no shrink); VolumeSnapshot + restore via dataSource |
| CSI | Controller plugin (Deployment + provisioner/attacher/resizer/snapshotter sidecars), node plugin (DaemonSet + registrar) |
| StatefulSet | volumeClaimTemplates → data-<sts>-<n>; PVCs retained; retention policy stable 1.32 |
| Databases | Operator (CloudNativePG, Percona, Zalando) or managed; WAL archive to object storage; PDBs; zone spread |
| Laravel | envFrom ConfigMap + Secret, config:cache at start, Reloader, emptyDir for framework, S3 for uploads |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — You changed LOG_LEVEL in a ConfigMap that the Deployment loads with envFrom, and an hour later the Pods still log at the old level. Why, and what are two ways to fix it? Must-know
Answer
Answer: Environment variables are resolved once, when the container is created; the docs say ConfigMaps consumed as environment variables "are not updated automatically and require a pod restart." Either trigger a rollout on every change (Reloader with reloader.stakater.com/auto: "true", a Helm checksum annotation, or a versioned ConfigMap name the Pod template points to), or move the value into a mounted ConfigMap directory and have the app watch and reload it. See Update propagation and Config reload.
2 — A mounted ConfigMap is updated, but the file the app reads at /etc/nginx/conf.d/tuning.conf never changes. What is the likely cause? Must-know
Answer
Answer: The file is mounted with subPath. A subPath mount bind-mounts the single file resolved at start; the kubelet updates the volume by swapping the ..data symlink to a new timestamped directory, which the bind mount never sees ("will not receive ConfigMap updates"). Mount the whole directory (and include it from the main config), or treat the file as restart-only and roll the Pods on change. See the atomic writer.
3 — Are Kubernetes Secrets encrypted? What would you check and change on a self-managed cluster? Must-know
Answer
Answer: Not by default: values are base64 in the API and stored as plain text in etcd unless kube-apiserver runs with --encryption-provider-config whose first provider is not identity. Check the flag and the file; configure a kms v2 provider (stable since v1.29) backed by a cloud KMS or HSM, restart every API server, rewrite all Secrets with kubectl get secrets --all-namespaces -o json | kubectl replace -f -, verify in etcd, and remove any identity fallback. Managed clusters expose the same as "envelope encryption" with a KMS key. See Encryption at rest.
4 — A developer has no get permission on Secrets in prod but can create Deployments there. Can they read the database password? Must-know
Answer
Answer: Yes. A Pod they create can mount any Secret in the namespace (the kubelet fetches it, not the developer), and the Secret page says anyone who can create a Pod "can use that access to read any Secret in that namespace; this includes indirect access such as the ability to create a Deployment." The same goes for list/watch on Secrets, which return the data. Treat the namespace as the trust boundary: no workload-create rights for humans in production namespaces, deploys only through CI/GitOps identities. See RBAC for secrets.
5 — Why prefer mounted secret files over secretKeyRef environment variables for a database password? Must-know
Answer
Answer: Files on tmpfs are updated in place when the Secret changes, so a rotated password reaches a process that re-reads the file without a restart; env vars are frozen until the Pod is replaced. Env vars also leak more easily (child processes, crash reports, /proc/<pid>/environ, debug pages). Files can be limited to one container and to the keys it needs (items) with a strict defaultMode. Use a *_FILE variable to point the app at the file. See Environment variables vs files.
6 — What is the difference between External Secrets Operator and the Secrets Store CSI Driver, and when would you choose each? Important
Answer
Answer: ESO is one controller that reads the external store (Vault, AWS Secrets Manager, Google Secret Manager, Azure Key Vault) with the store's identity and writes ordinary Kubernetes Secrets on a refreshInterval; Pods consume them as usual and keep working if the store is briefly down. The CSI driver is a privileged DaemonSet with a provider per node that fetches secrets at Pod start using the Pod's own ServiceAccount identity and mounts them as tmpfs files, with no Secret object unless secretObjects is set; rotation is an alpha feature and new Pods fail if the store is down. Choose ESO by default; choose the CSI driver when secret material must not be stored in etcd or each Pod must authenticate as itself. See ESO and Secrets Store CSI.
7 — How do Sealed Secrets and SOPS keep secrets safe in a GitOps repository, and what does each cost? Important
Answer
Answer: Sealed Secrets: kubeseal encrypts with the controller's public key; only the in-cluster controller can decrypt and create the Secret; the default strict scope binds the ciphertext to name and namespace. Cost: per-cluster keys to back up, re-sealing for each cluster. SOPS: encrypts the values (keys stay readable) of a normal manifest with KMS, age or PGP, chosen by .sops.yaml rules; Flux decrypts natively, Argo CD needs a plugin. Cost: KMS/age key management and tooling in the GitOps controller. With either, a leaked secret must be rotated at its source. See GitOps secrets.
8 — A Deployment with one replica and a ReadWriteOnce PVC hangs on every rollout with a Multi-Attach error. Explain and fix. Important
Answer
Answer: The default RollingUpdate creates the new Pod before deleting the old one. If the new Pod lands on another node, the RWO disk is still attached to the old node, so the new Pod cannot start, and the old Pod is not removed until the new one is Ready: a deadlock. Use strategy: Recreate (accepting a short gap), or a StatefulSet; ReadWriteOncePod additionally guarantees only one Pod ever mounts it. GKE's docs warn against exactly this pattern. See Access modes.
9 — Why should StorageClasses for zonal cloud disks use volumeBindingMode: WaitForFirstConsumer? Important
Answer
Answer: With the default Immediate, the disk is created as soon as the PVC exists, "without knowledge of the Pod's scheduling requirements", possibly in a zone where the Pod cannot run (no capacity, affinity, spread constraints), leaving it unschedulable with a volume node affinity conflict. WaitForFirstConsumer delays provisioning until the scheduler has chosen a node, and the provisioner creates the disk in that node's zone. Do not combine it with nodeName, which bypasses the scheduler and leaves the PVC pending. See StorageClass.
10 — Someone deleted a PVC by mistake. When is the data gone, and how do you make this survivable? Must-know
Answer
Answer: If the PV's reclaim policy is Delete (the StorageClass default), the CSI driver deletes the backing disk as soon as the PVC is released, and the data is gone unless a snapshot or backup exists. With Retain, the PV becomes Released and the disk stays; an admin can create a new PV for the same volume handle and bind a new PVC to it. Make it survivable with Retain classes for data, VolumeSnapshots before risky changes, and real backups off-cluster (WAL archive to object storage for databases). See Reclaim policy.
11 — What does a CloudNativePG cluster give you that a hand-written PostgreSQL StatefulSet does not? Important
Answer
Answer: Automated failover (promote a standby, repoint the -rw Service), switchover before a node drain, operator-managed PodDisruptionBudgets, streaming replication setup, WAL archiving and base backups to object storage (Barman Cloud plugin) or volume snapshots, declarative recovery and PITR into a new cluster, rolling minor upgrades, PVC management and resizing, and a generated <cluster>-app Secret with a connection URI. A StatefulSet only gives stable names and per-replica PVCs. See Databases on Kubernetes.
12 — In a Laravel app on Kubernetes, why must php artisan config:cache run at container start rather than in the Dockerfile, and what follows for Secret rotation? Important
Answer
Answer: Once config is cached, "the env function will only return external, system level environment variables" and the cached file holds the values that were present when the command ran. In a Dockerfile that is the build environment, so production would run with build-time (or empty) values. Run it in the entrypoint, after envFrom has injected the ConfigMap and Secret. Because the values are frozen per Pod, a rotated Secret reaches Laravel only through new Pods: add Reloader or a checksum annotation. See The Laravel angle.
13 — Why does the Go watcher in this chapter watch the directory and ignore event types, instead of watching log_level? Good to know
Answer
Answer: The kubelet never writes log_level: it writes a new hidden timestamped directory and atomically renames ..data_tmp over ..data, so a watch on the file (which follows the symlink to the old directory) sees only that directory being deleted and then nothing. The events of one update are several and platform-dependent (13 on macOS kqueue in the lab), so the watcher debounces any event in the directory, re-reads all keys, compares bytes, validates, and swaps an atomic.Pointer. fsnotify's README gives the same advice for editors that save atomically. See Go.
14 — Where should Laravel user uploads live on Kubernetes, and why not on a PersistentVolumeClaim? Good to know
Answer
Answer: In object storage through the s3 disk (S3 or an S3-compatible store), with credentials from IRSA or Workload Identity. A PVC would need ReadWriteMany to be shared by replicas on several nodes, ties the web tier to one storage system (often slow NFS), complicates zone spread and backups, and is invisible to a CDN; emptyDir is fine only for per-Pod scratch such as storage/framework. See Storage volume vs S3.
Glossary
| Term | Meaning |
|---|---|
| ConfigMap | Namespaced API object holding non-secret key/value data (data, binaryData), at most 1 MiB |
| envFrom | Container field importing all keys of a ConfigMap (configMapRef) or Secret (secretRef) as env vars |
| configMapKeyRef | env[].valueFrom source taking one key of a ConfigMap as one env var |
| secretKeyRef | env[].valueFrom source taking one key of a Secret as one env var |
| mounted ConfigMap | ConfigMap projected as a directory of files, refreshed in place by the kubelet |
| mounted secret | Secret projected as files on tmpfs, refreshed in place by the kubelet |
| immutable ConfigMap | ConfigMap (or Secret) with immutable: true: data cannot change, watches closed (stable v1.21) |
| kubelet sync period | syncFrequency (default 1m): max time between the kubelet's syncs of a Pod's containers and volumes |
| subPath | volumeMounts[].subPath: mount one path of a volume; for ConfigMap/Secret volumes it never updates |
| atomic writer | Kubelet helper writing a timestamped directory and swapping the ..data symlink with one rename |
| Secret | Namespaced object for confidential data, base64 in data, at most 1MiB |
| Opaque | Default Secret type for arbitrary data |
| kubernetes.io/tls | Secret type with tls.crt and tls.key |
| dockerconfigjson | kubernetes.io/dockerconfigjson: registry credentials for imagePullSecrets |
| base64 | Binary-to-text encoding used for Secret data; trivially reversible, not encryption |
| encryption at rest | API server encrypting resources before writing them to etcd |
| EncryptionConfiguration | apiserver.config.k8s.io/v1 file listing ordered providers per resource |
| KMS provider | Envelope-encryption provider calling an external KMS plugin over gRPC on a Unix socket (v2 stable 1.29) |
| RBAC for secrets | Rules on secrets: get by resourceNames is narrow; list/watch reveal all data |
| environment variables vs files | The choice between env injection (frozen, leak-prone) and mounted files (rotatable, scoped) |
| External Secrets Operator | Controller syncing secrets from external stores into Kubernetes Secrets (ESO) |
| ExternalSecret | ESO resource: what to fetch, which Secret to write, refresh and ownership policy |
| SecretStore | ESO resource: how to reach and authenticate to a provider (namespaced; ClusterSecretStore is cluster-wide) |
| Secrets Store CSI Driver | SIG Auth CSI driver mounting secrets from external stores as tmpfs files at Pod start |
| SecretProviderClass | CSI driver resource naming a provider and the objects to mount |
| Vault | HashiCorp secret manager; Kubernetes auth via ServiceAccount tokens and TokenReview |
| Sealed Secrets | Controller plus kubeseal; asymmetric encryption so only the cluster can decrypt |
| SOPS | Editor of encrypted files (values encrypted, keys clear) with KMS, age or PGP |
| GitOps secrets | Patterns for keeping secrets out of, or encrypted in, the Git repository GitOps applies |
| config reload | Making a running workload use changed configuration: rollout or in-process reload |
| checksum annotation | Pod-template annotation holding a hash of a config file so a change triggers a rollout (Helm sha256sum) |
| Reloader | Stakater controller rolling workloads when referenced ConfigMaps or Secrets change |
| hot reload | The process re-reads configuration without restarting (file watch, polling) |
| fsnotify | Go file-system notification library (inotify, kqueue, ReadDirectoryChangesW) |
| viper preview | spf13/viper: config library with WatchConfig/OnConfigChange built on fsnotify (not used in the module) |
| Go config loading | Reading env (static) and mounted files (dynamic) into typed, validated config in Go |
| Volume | Directory available to a Pod's containers, declared in .spec.volumes |
| emptyDir | Pod-lifetime scratch volume on node storage or RAM (medium: Memory) |
| hostPath | Volume exposing a node path; many security risks |
| projected volume | One directory combining Secret, ConfigMap, downwardAPI, serviceAccountToken and other sources |
| downwardAPI | Exposes Pod fields (name, labels, limits) as env vars or files |
| PersistentVolume | Cluster-scoped record of one piece of storage, lifecycle independent of Pods (PV) |
| PersistentVolumeClaim | Namespaced request for storage: size, access modes, class (PVC) |
| StorageClass | Cluster-scoped recipe for dynamic provisioning: provisioner, parameters, policies |
| dynamic provisioning | Creating a PV automatically for a PVC through its StorageClass's provisioner |
| provisioner | The driver named by a StorageClass (e.g. ebs.csi.aws.com); for CSI, the external-provisioner sidecar acts for it |
| WaitForFirstConsumer | volumeBindingMode delaying binding/provisioning until a Pod is scheduled |
| topology | Zone/node constraints of storage, carried as PV node affinity and CSI accessibility |
| access modes | ReadWriteOnce, ReadOnlyMany, ReadWriteMany, ReadWriteOncePod: matching and attach rules for PVs |
| ReadWriteOnce | Read-write by a single node (RWO) |
| ReadWriteMany | Read-write by many nodes (RWX), shared file systems |
| ReadWriteOncePod | Read-write by a single Pod cluster-wide (RWOP), CSI only, stable v1.29 |
| reclaimPolicy | What happens to a PV after its claim is deleted: Retain, Delete (default for dynamic), Recycle (deprecated) |
| volume expansion | Growing a PVC by raising its request when allowVolumeExpansion is true (stable v1.24) |
| VolumeSnapshot | CRD requesting a point-in-time snapshot of a PVC (CSI only, stable v1.20) |
| CSI driver | Storage plugin implementing the Container Storage Interface gRPC services |
| node plugin | Per-node CSI component (DaemonSet) the kubelet calls to stage and publish volumes |
| controller plugin | Central CSI component (Deployment/StatefulSet) with sidecars for provisioning, attach, resize, snapshots |
| volumeClaimTemplates | StatefulSet field creating one PVC per replica (<template>-<sts>-<ordinal>) |
| local PV | Statically created PV for a node-local disk, pinned by node affinity |
| databases on Kubernetes | Running stateful database engines in the cluster, normally through an operator |
| operators | Controllers encoding operational knowledge for an application through custom resources |
| CloudNativePG | CNCF PostgreSQL operator: streaming replication, failover, -rw/-ro Services, Barman Cloud backups |
| Percona Operator | Percona's operators for PostgreSQL (based on Crunchy Data's PGO) and MySQL |
| Zalando postgres-operator | Patroni-based PostgreSQL operator configured through CRD manifests |
| managed database vs in-cluster | Choosing a cloud database service or an operator-run database inside Kubernetes |
| backups to object storage | WAL archive and base backups sent to S3/GCS/Azure Blob, the basis of PITR |
| PodDisruptionBudget for databases | PDBs limiting voluntary evictions so drains never take a primary and its replicas at once |
| Laravel .env from Secret | Supplying Laravel's settings as env vars from a ConfigMap and a Secret instead of a .env file |
| config:cache | Artisan command caching config; afterwards env() returns only real environment variables |
| storage volume vs S3 | Per-Pod emptyDir for framework scratch versus object storage for user uploads |
References
- Kubernetes configuration: ConfigMaps https://kubernetes.io/docs/concepts/configuration/configmap/ — Secrets https://kubernetes.io/docs/concepts/configuration/secret/ — Good practices for Secrets https://kubernetes.io/docs/concepts/security/secrets-good-practices/
- Kubernetes tasks: configure a Pod to use a ConfigMap https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/ — distribute credentials securely https://kubernetes.io/docs/tasks/inject-data-application/distribute-credentials-secure/ — expose Pod information as env vars https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/ — define environment variables https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/ — downward API https://kubernetes.io/docs/concepts/workloads/pods/downward-api/
- Encryption at rest https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/ — KMS provider https://kubernetes.io/docs/tasks/administer-cluster/kms-provider/
- RBAC https://kubernetes.io/docs/reference/access-authn-authz/rbac/ — RBAC good practices https://kubernetes.io/docs/concepts/security/rbac-good-practices/
- Kubelet configuration (
syncFrequency,configMapAndSecretChangeDetectionStrategy) https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/ — kubelet atomic writer https://github.com/kubernetes/kubernetes/blob/master/pkg/volume/util/atomic_writer.go - Kubernetes storage: volumes https://kubernetes.io/docs/concepts/storage/volumes/ — volume types https://kubernetes.io/docs/reference/storage/volume-types/ — projected volumes https://kubernetes.io/docs/concepts/storage/projected-volumes/ — ephemeral volumes https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/ — persistent volumes https://kubernetes.io/docs/concepts/storage/persistent-volumes/ — storage classes https://kubernetes.io/docs/concepts/storage/storage-classes/ — dynamic provisioning https://kubernetes.io/docs/concepts/storage/dynamic-provisioning/ — volume snapshots https://kubernetes.io/docs/concepts/storage/volume-snapshots/ — snapshot classes https://kubernetes.io/docs/concepts/storage/volume-snapshot-classes/ — cloning https://kubernetes.io/docs/concepts/storage/volume-pvc-datasource/
- StatefulSets https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/ — feature gates https://kubernetes.io/docs/reference/command-line-tools-reference/feature-gates/ — releases https://kubernetes.io/releases/
- Kubernetes CSI documentation https://kubernetes-csi.github.io/docs/ — deploying https://kubernetes-csi.github.io/docs/deploying.html — developing https://kubernetes-csi.github.io/docs/developing.html — sidecars https://kubernetes-csi.github.io/docs/sidecar-containers.html — CSI specification https://github.com/container-storage-interface/spec/blob/master/spec.md
- External Secrets Operator https://external-secrets.io/latest/ — overview https://external-secrets.io/latest/introduction/overview/ — ExternalSecret https://external-secrets.io/latest/api/externalsecret/ — Vault provider https://external-secrets.io/latest/provider/hashicorp-vault/ — AWS Secrets Manager https://external-secrets.io/latest/provider/aws-secrets-manager/
- Secrets Store CSI Driver https://secrets-store-csi-driver.sigs.k8s.io/ — concepts https://secrets-store-csi-driver.sigs.k8s.io/concepts.html — rotation https://secrets-store-csi-driver.sigs.k8s.io/topics/secret-auto-rotation.html — sync as Secret https://secrets-store-csi-driver.sigs.k8s.io/topics/sync-as-kubernetes-secret.html — Vault CSI provider https://developer.hashicorp.com/vault/docs/platform/k8s/csi
- Sealed Secrets https://github.com/bitnami-labs/sealed-secrets — SOPS https://github.com/getsops/sops and docs https://getsops.io/docs/ — Reloader https://github.com/stakater/Reloader — Helm tips (automatically roll deployments) https://helm.sh/docs/howto/charts_tips_and_tricks/
- CloudNativePG: architecture https://cloudnative-pg.io/documentation/current/architecture/ — backup https://cloudnative-pg.io/documentation/current/backup/ — failover https://cloudnative-pg.io/documentation/current/failover/ — Kubernetes upgrades and PDBs https://cloudnative-pg.io/documentation/current/kubernetes_upgrade/ — connecting applications https://cloudnative-pg.io/documentation/current/applications/ — Barman Cloud plugin https://cloudnative-pg.io/plugin-barman-cloud/docs/usage/ — CNCF blog, Recommended Architectures for PostgreSQL in Kubernetes https://www.cncf.io/blog/2023/09/29/recommended-architectures-for-postgresql-in-kubernetes/
- Zalando postgres-operator https://github.com/zalando/postgres-operator — Percona Operator for PostgreSQL https://github.com/percona/percona-postgresql-operator — Percona Operator for MySQL https://github.com/percona/percona-server-mysql-operator — Strimzi https://github.com/strimzi/strimzi-kafka-operator — RabbitMQ Cluster Operator https://github.com/rabbitmq/cluster-operator — OT-CONTAINER-KIT redis-operator https://github.com/OT-CONTAINER-KIT/redis-operator
- AWS EBS CSI driver https://github.com/kubernetes-sigs/aws-ebs-csi-driver — parameters https://github.com/kubernetes-sigs/aws-ebs-csi-driver/blob/master/docs/parameters.md — multi-attach https://github.com/kubernetes-sigs/aws-ebs-csi-driver/blob/master/docs/multi-attach.md — EKS EBS CSI https://docs.aws.amazon.com/eks/latest/userguide/ebs-csi.html — GKE persistent volumes https://cloud.google.com/kubernetes-engine/docs/concepts/persistent-volumes — local static provisioner https://github.com/kubernetes-sigs/sig-storage-local-static-provisioner
- Go: fsnotify https://github.com/fsnotify/fsnotify — viper https://github.com/spf13/viper
- Laravel 13: configuration https://laravel.com/docs/13.x/configuration — file storage https://laravel.com/docs/13.x/filesystem — deployment https://laravel.com/docs/13.x/deployment