StackPractices
advanced By Mathias Paulenko

Kubernetes Config Management Guide

Kubernetes configuration management: ConfigMaps, Secrets, External Secrets Operator, sealed secrets, env injection, mounts, and rotation.

Topics: devops

Introduction

Every production Kubernetes cluster runs on configuration — feature flags, database endpoints, credentials, certificates — and the way you manage it determines how many of your incidents start with “the wrong value was deployed.” Kubernetes splits the problem cleanly: ConfigMaps for non-sensitive config, Secrets for anything you’d regret leaking, and operators like External Secrets and Sealed Secrets for keeping credentials out of Git while staying GitOps-friendly.

This guide covers the mechanics that matter: how to create and inject ConfigMaps and Secrets, when env vars vs volume mounts change the behavior of your app, how config actually propagates to running pods (it isn’t instant), when to reach for External Secrets Operator vs Sealed Secrets vs a Vault agent, and how rotation works without downtime. For the complementary GitOps side, the ArgoCD guide covers delivery; this one covers what’s delivered.

If you’re mounting configs into pods already, the ConfigMap/Secret mounting recipe is the short-form version of the patterns here.

Choosing an Injection Method

Before the YAML, the decision that shapes everything else: environment variables or volume mounts?

MethodUpdates propagate?Reads atBest for
env / envFromNo — requires pod restartProcess startStatic config: endpoints, flags
Volume mountYes — ~60-90s via kubelet syncFile read (each access)Config files, hot-reload apps
subPath mountNo — updates don’t propagateFile readSingle file from a larger ConfigMap
Projected volumeYesFile readCombining ConfigMaps + Secrets

Two gotchas the table hides: env vars are set at container start, so a ConfigMap change does nothing until you restart the pod — the single most common “why didn’t my config update” question. And subPath mounts never get updates at all, which surprises everyone the first time.

One more practical consideration: mounted files arrive through a tmpfs-backed volume, so they’re memory-resident and fast to read — but they count against the pod’s memory. A 1MB ConfigMap mounted in a 512Mi pod is a real fraction of the limit; oversized ConfigMaps fail with a clear error at pod admission, not a silent truncation.

ConfigMaps

ConfigMaps store non-sensitive configuration as key-value pairs — or whole files. They’re plain text, namespace-scoped, and capped at 1MB by etcd, which is why “put the whole application config in a ConfigMap” fails on large bundles.

Create a ConfigMap

# k8s/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: production
  # Immutable ConfigMaps can't be changed — faster reads, safer deploys
  immutable: true
data:
  # Key-value pairs
  LOG_LEVEL: "info"
  DATABASE_HOST: "db.internal"
  DATABASE_PORT: "5432"
  REDIS_URL: "redis://redis:6379"

  # Full file content as a key
  nginx.conf: |
    server {
      listen 80;
      location / {
        proxy_pass http://backend:3000;
      }
    }

  config.json: |
    {
      "feature_flags": {
        "new_ui": true,
        "beta_features": false
      },
      "limits": {
        "max_connections": 100
      }
    }

immutable: true does two useful things: it makes accidental edits impossible (any change requires deleting and recreating the ConfigMap — so your GitOps flow is the only path), and it lets the kubelet skip the watch for updates, which measurably reduces API server load in clusters with many ConfigMaps.

Create from files

# Create ConfigMap from a single file
kubectl create configmap nginx-config --from-file=nginx.conf

# Create from multiple files
kubectl create configmap app-config \
    --from-file=config.json \
    --from-file=settings.yaml \
    --from-file=nginx.conf

# Create from a directory
kubectl create configmap app-config --from-file=./config/

# Create from literal values
kubectl create configmap app-config \
    --from-literal=LOG_LEVEL=info \
    --from-literal=DATABASE_HOST=db.internal

The file-based flags keep the filename as the ConfigMap key — handy for dropping an existing application.properties or nginx.conf straight in. In a GitOps repo you usually generate ConfigMaps from the same files your developers edit, so the review diff is the config diff.

Inject ConfigMap as environment variables

# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
spec:
  template:
    spec:
      containers:
        - name: app
          image: my-app:latest
          env:
            # Single value from ConfigMap
            - name: LOG_LEVEL
              valueFrom:
                configMapKeyRef:
                  name: app-config
                  key: LOG_LEVEL

            - name: DATABASE_HOST
              valueFrom:
                configMapKeyRef:
                  name: app-config
                  key: DATABASE_HOST

          # All ConfigMap keys as env vars
          envFrom:
            - configMapRef:
                name: app-config
                optional: false  # Pod fails if ConfigMap doesn't exist

envFrom with optional: false is the fail-fast setting you want for anything critical — a missing ConfigMap then kills the pod at admission instead of starting it with empty env vars and failing mysteriously later. Use env per-key when the pod only needs one or two values; envFrom when it needs the whole set.

Mount ConfigMap as a file

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
spec:
  template:
    spec:
      containers:
        - name: app
          image: my-app:latest
          volumeMounts:
            - name: config-volume
              mountPath: /etc/config
              readOnly: true

      volumes:
        - name: config-volume
          configMap:
            name: app-config
            # Optional: specify which keys to include
            items:
              - key: config.json
                path: config.json
              - key: nginx.conf
                path: nginx.conf

Volume mounts give you the hot-reload path: kubelet updates the mounted files roughly every sync period (60-90s), so an app that re-reads its config file picks up changes without a restart. Your app still has to watch the file or re-read it — Kubernetes updates the files, it doesn’t signal your process.

Mount ConfigMap with subPath (single file)

volumes:
  - name: config-volume
    configMap:
      name: app-config

containers:
  - name: app
    volumeMounts:
      - name: config-volume
        mountPath: /app/config.json
        subPath: config.json  # Mounts only this key
        readOnly: true

Use subPath when you need one file out of a multi-key ConfigMap into an existing directory — but know the trade: subPath mounts are resolved once at container start and never receive updates. If you need hot reload, mount the whole volume instead.

Secrets

Secrets are ConfigMaps with base64 encoding plus real controls layered on top: RBAC-restricted access, etcd encryption at rest (when enabled), and the assumption that values shouldn’t show up in kubectl get cm -o yaml output. Base64 is encoding, not encryption — the security comes from access control and etcd encryption, not the format.

Create a Secret

# k8s/secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
  namespace: production
type: Opaque
data:
  # Base64-encoded values
  DATABASE_PASSWORD: cGFzc3dvcmQxMjM=  # echo -n "password123" | base64
  API_KEY: YWJjZGVmZ2hpamtsbW5vcA==
  JWT_SECRET: c3VwZXItc2VjcmV0LWtleQ==
stringData:
  # Plain text values (auto-encoded by Kubernetes)
  DATABASE_URL: "postgresql://user:pass@db:5432/myapp"
  STRIPE_KEY: "sk_live_abc123"

stringData writes plain text and lets the API server encode it — safer for hand-editing since a malformed base64 value in data gets silently accepted. Never mix data and stringData for the same key: data wins and your stringData entry is ignored.

Create from CLI

# Create from literal values
kubectl create secret generic app-secrets \
    --from-literal=DATABASE_PASSWORD=password123 \
    --from-literal=API_KEY=abcdefg

# Create from file
kubectl create secret generic tls-secret \
    --from-file=tls.crt=cert.pem \
    --from-file=tls.key=key.pem

# Create Docker registry secret
kubectl create secret docker-registry registry-secret \
    --docker-server=registry.io \
    --docker-username=user \
    --docker-password=pass \
    --docker-email=email@example.com

Inject Secret as environment variables

containers:
  - name: app
    env:
      - name: DATABASE_PASSWORD
        valueFrom:
          secretKeyRef:
            name: app-secrets
            key: DATABASE_PASSWORD
      - name: API_KEY
        valueFrom:
          secretKeyRef:
            name: app-secrets
            key: API_KEY

    # All Secret keys as env vars
    envFrom:
      - secretRef:
          name: app-secrets

Env vars are the most common leak path for secrets — they show up in kubectl describe pod, in crash logs, in env output when debugging, and in process listings. For anything sensitive, prefer volume mounts: the value only exists as a file in the container’s filesystem.

Mount Secret as files

volumes:
  - name: secret-volume
    secret:
      secretName: app-secrets
      defaultMode: 0400  # Read-only by owner

containers:
  - name: app
    volumeMounts:
      - name: secret-volume
        mountPath: /etc/secrets
        readOnly: true

defaultMode sets the file permissions inside the volume — 0400 (owner-read only) is the right default for credentials. fsGroup on the pod’s securityContext controls group ownership if your app runs non-root and needs read access.

TLS Secret

apiVersion: v1
kind: Secret
metadata:
  name: tls-secret
type: kubernetes.io/tls
data:
  tls.crt: <base64-encoded-cert>
  tls.key: <base64-encoded-key>
# Create TLS secret from files
kubectl create secret tls tls-secret \
    --cert=cert.pem \
    --key=key.pem

The kubernetes.io/tls type validates that both keys exist and look like PEM — use it for ingress TLS termination rather than generic Opaque secrets.

External Secrets Operator vs Sealed Secrets

Once secrets stop being hand-rolled YAML, you pick an operator. The three real options solve the same problem — “secrets in a source of truth, not in Git” — differently:

ApproachHow it worksSecrets live inGood when
External Secrets OperatorSyncs from external manager into k8s SecretsVault, AWS/GCP/Azure secret managersYou already run a secret manager
Sealed SecretsEncrypts secrets so they’re safe in GitGit (encrypted), cluster key (decrypt)GitOps-first, no external manager
Vault Agent InjectorSidecar/mutating webhook injects directlyVault onlyAll-in on Vault, want no k8s Secrets

ESO is the most flexible — it normalizes any backend into a standard k8s Secret, so your app stays ignorant of where the secret came from. Sealed Secrets is the simplest for pure GitOps: kubeseal produces an encrypted blob that only your cluster can open, so it goes straight into the repo next to the Deployment. Vault Agent Injector skips the k8s Secret layer entirely — strongest isolation, but locks you to Vault and adds a sidecar per pod.

External Secrets Operator

Install ESO

# Install via Helm
helm install external-secrets \
    external-secrets/external-secrets \
    --namespace external-secrets \
    --create-namespace

SecretStore (connects to Vault)

apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
  name: vault-backend
  namespace: production
spec:
  provider:
    vault:
      server: "https://vault.internal:8200"
      path: "kv"
      version: "v2"
      auth:
        kubernetes:
          mountPath: "kubernetes"
          role: "external-secrets"
          serviceAccountRef:
            name: external-secrets

A SecretStore is namespaced — use ClusterSecretStore when one backend serves several namespaces. The auth method above uses the Kubernetes auth role, so no static credentials ever touch the cluster.

ExternalSecret (syncs from Vault to Kubernetes Secret)

apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: app-secrets
  namespace: production
spec:
  refreshInterval: 1h  # Sync every hour
  secretStoreRef:
    name: vault-backend
    kind: SecretStore
  target:
    name: app-secrets  # Name of the Kubernetes Secret to create
    creationPolicy: Owner
  data:
    - secretKey: DATABASE_PASSWORD
      remoteRef:
        key: production/database
        property: password
    - secretKey: API_KEY
      remoteRef:
        key: production/api
        property: key
    - secretKey: JWT_SECRET
      remoteRef:
        key: production/auth
        property: jwt_secret

refreshInterval controls how often ESO re-pulls the external value — rotate in Vault, and the cluster gets the new value within the interval. creationPolicy: Owner ties the created Secret’s lifecycle to the ExternalSecret, so deleting the ExternalSecret cleans up the Secret too.

External Secrets Operator flow: the ESO controller polls a SecretStore pointing at Vault or AWS Secrets Manager and materializes a standard Kubernetes Secret that pods consume like any other.

AWS Secrets Manager SecretStore

apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
  name: aws-secrets
spec:
  provider:
    aws:
      service: SecretsManager
      region: us-east-1
      auth:
        jwt:
          serviceAccountRef:
            name: external-secrets

Same shape, different provider — the jwt auth references the service account’s IRSA token on EKS. Your manifests stay identical across backends; only the SecretStore changes.

Sealed Secrets

Install Sealed Secrets controller

helm install sealed-secrets \
    sealed-secrets/sealed-secrets \
    --namespace kube-system \
    --create-namespace

Seal a secret

# Create a regular secret, then seal it
echo -n 'password123' | base64 > secret.yaml
cat > secret.yaml <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
  namespace: production
type: Opaque
data:
  DATABASE_PASSWORD: cGFzc3dvcmQxMjM=
EOF

# Seal it (safe to commit to Git)
kubeseal --format yaml < secret.yaml > sealed-secret.yaml

kubeseal encrypts against the cluster’s public key — the output’s useless outside it, so committing it is safe. Scope matters: by default a SealedSecret is namespace-scoped, so app-secrets in staging can’t be opened by production. Use --scope cluster-wide only when you deliberately want that.

SealedSecret resource

apiVersion: bitnami.com/v1alpha1
kind: SealedSecret
metadata:
  name: app-secrets
  namespace: production
spec:
  encryptedData:
    DATABASE_PASSWORD: AgB...encrypted-blob...
  template:
    metadata:
      name: app-secrets
      namespace: production
    type: Opaque

Config Rotation

Mounted ConfigMaps update on their own (~60-90s), but env-var config and most app codepaths never re-read it. Rotation solves this: make pod restarts part of the config-change path.

Restart pods on ConfigMap change

# ConfigMap change doesn't auto-restart pods.
# Use a hash annotation to force restart on config change.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
spec:
  template:
    metadata:
      annotations:
        # Hash of ConfigMap content — changes when ConfigMap updates
        checksum/config: "{{ .Values.configHash }}"
    spec:
      containers:
        - name: app
          envFrom:
            - configMapRef:
                name: app-config

The checksum trick is the Helm-native approach: any change to configHash updates the pod template annotation, which triggers a rolling update — no new controller needed, and the restart is gradual rather than a mass bounce.

Reloader (automatic restart on config change)

# Install Reloader — auto-restarts pods when ConfigMaps/Secrets change
helm install reloader stakater/reloader \
    --namespace reloader \
    --create-namespace
# Annotate deployment to trigger restart on ConfigMap/Secret change
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  annotations:
    configmap.reloader.stakater.com/reload: "app-config"
    secret.reloader.stakater.com/reload: "app-secrets"

Reloader watches the named resources and rolls the Deployment when they change — less YAML juggling than checksums once you’ve got a fleet of deployments, at the cost of one more controller in the cluster.

RBAC and Security for Secrets

Secrets are only as safe as who can read them. Scope access tightly:

# Only this service account can read app-secrets
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: app-secrets-reader
  namespace: production
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    resourceNames: ["app-secrets"]
    verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: app-secrets-reader
  namespace: production
subjects:
  - kind: ServiceAccount
    name: app
    namespace: production
roleRef:
  kind: Role
  name: app-secrets-reader
  apiGroup: rbac.authorization.k8s.io

Three layers that work together: resourceNames restricts to specific secrets (avoid * on secrets — it hands every pod the keys to everything), etcd encryption at rest protects the data if the etcd store is compromised, and immutable: true on ConfigMaps prevents config drift between deploys. If you’re on EKS/GKE/AKS, enable the managed etcd encryption option — it uses your cloud KMS and costs almost nothing.

Best Practices

  • Use ConfigMaps for non-sensitive config — environment variables, feature flags, config files
  • Use Secrets for sensitive data — passwords, tokens, API keys, certificates
  • Never store Secrets in Git as plain text — use External Secrets Operator or Sealed Secrets
  • Use envFrom for bulk injection — cleaner than listing each variable individually
  • Use volume mounts for config files — lets your app hot reload without pod restart (with Reloader)
  • Use External Secrets Operator for production — syncs from Vault, AWS Secrets Manager, GCP Secret Manager
  • Use Sealed Secrets for GitOps — encrypted secrets safe to commit to version control
  • Set optional: false on critical ConfigMaps — pod fails fast if config is missing
  • Use defaultMode: 0400 on Secret volumes — restrict file permissions
  • Use Reloader for automatic restarts — pods pick up config changes without manual intervention
  • Namespace your config — use separate ConfigMaps per application or service
  • Use immutable: true for static config — improves performance and prevents accidental changes

Common Mistakes

  • Storing secrets in ConfigMaps: ConfigMaps aren’t encrypted. Use Secrets or External Secrets Operator.
  • Committing base64 secrets to Git: base64 is encoding, not encryption. Anyone can decode. Use Sealed Secrets or ESO.
  • No config rotation: updating a ConfigMap doesn’t restart pods. Use Reloader or checksum annotations.
  • Mounting entire ConfigMap when you need one file: use subPath to mount a single key as a file.
  • No namespace scoping: ConfigMaps are namespace-scoped. A ConfigMap in default namespace is invisible to production.
  • Using stringData and data for the same key: data takes precedence. Use one or the other per key.

See Also

All manifests on this page ship as runnable files in the companion repository — ConfigMap/Secret/ExternalSecret/SealedSecret YAML, Reloader values, and a kind cluster script for local testing.

Frequently Asked Questions

What is the difference between ConfigMap and Secret?

ConfigMaps store non-sensitive configuration as plain key-value pairs. Secrets store sensitive data with base64 encoding plus access controls (RBAC, etcd encryption at rest). Use ConfigMaps for app config, Secrets for credentials — the security is in the controls, not the base64.

Are Kubernetes Secrets encrypted?

By default, no — they're base64-encoded, which is encoding, not encryption. Enable encryption at rest in etcd with --encryption-provider-config, or rely on your managed provider's KMS integration. For real secret lifecycle management, use External Secrets Operator with Vault or a cloud secret manager.

When should I use a volume mount instead of env vars?

Use a mount when the config changes without deploys — volume-mounted ConfigMaps update in ~60-90s and your app can watch the file. Env vars are simpler but static: they only populate at container start, so a change requires a restart. For secrets specifically, mounts also keep values out of process listings and crash dumps.

What is External Secrets Operator?

An operator that syncs secrets from external secret managers (Vault, AWS Secrets Manager, GCP Secret Manager) into Kubernetes Secrets. You define an ExternalSecret pointing at a SecretStore, and ESO keeps the Kubernetes Secret updated — your app never knows the difference.

What are Sealed Secrets?

A controller that encrypts Kubernetes Secrets into SealedSecret resources safe to commit to Git. Only the cluster holding the private key can decrypt them — the ciphertext is useless elsewhere. The right fit for GitOps repos where manifests and secrets need to live together.

How do I update pod config without restarting?

Mount the ConfigMap as a volume — updates propagate in ~60-90s via kubelet sync, and your app picks them up if it re-reads the file. Env vars never update without a restart. For env-var configs specifically, use Reloader to automate the restart on change.

Can I mount a ConfigMap and a Secret in the same pod?

Yes — use a projected volume to combine several sources into one mount, or just declare two separate volumes with different mountPath values. There's no limit on how many ConfigMaps/Secrets a pod can mount beyond the 1MB-per-object size cap.