StackPractices
intermediate By Mathias Paulenko

Mount Configs and Secrets into Kubernetes Pods

How to mount ConfigMaps and Secrets into Kubernetes pods using env vars, volumes, projected volumes, and external secret managers.

Topics: devops

Overview

Any non-trivial deployment needs two kinds of configuration: values that change per environment (endpoints, feature flags, log levels) and credentials that should never live inside the image. Kubernetes splits that problem into ConfigMaps and Secrets, then gives you two ways to get them into a running pod: environment variables, or files mounted through a volume. The choice isn’t cosmetic — it decides whether the app sees config updates at all, which filesystem permissions apply, and how painful a rollback is.

This recipe covers the injection patterns you actually need in production: creating ConfigMaps and Secrets, loading them as env vars or mounting them as files, combining sources with projected volumes, and keeping credentials out of Git with External Secrets or Sealed Secrets. For the long-form version with the decision-making context, see the Kubernetes Config Management guide.

When to Use

  • Injecting per-environment configuration (dev, staging, prod) without rebuilding the image.
  • Passing database connection strings, API keys, or certificates to containers.
  • Shipping a whole config file like nginx.conf or application.yaml instead of individual values.
  • Updating configuration without restarting pods: volume mounts propagate changes, env vars don’t.
  • Mounting TLS certificates that must exist as files on disk.
  • Keeping secrets out of Git while staying GitOps-friendly.

When NOT to Use

  • For config that never changes: bake it into the image at build time. Simpler, faster, one less object to manage.
  • When the pod needs heavy templating: render manifests with Helm or Kustomize, or generate the file in an init container.
  • For secrets that must never touch etcd: use a CSI secrets driver or an agent sidecar that reads your vault directly.
  • When pods need to write back to shared config: ConfigMap and Secret volumes are read-only by design. Use a shared PVC or a proper config service.

Solution

Create a ConfigMap

A ConfigMap holds key-value pairs or whole files, capped at 1 MiB per object. data accepts literal values and multi-line strings.

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: default
data:
  LOG_LEVEL: "info"
  DATABASE_HOST: "db.internal"
  APP_PORT: "8080"
  config.yaml: |
    server:
      port: 8080
      timeout: 30s
    database:
      pool_size: 10
      timeout: 5s

Create a Secret

stringData accepts plaintext and Kubernetes base64-encodes it for you; use data only when the values are already encoded. Base64 is encoding, not encryption: the protection comes from RBAC and etcd encryption at rest, not from the format.

apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
  namespace: default
type: Opaque
stringData:
  DATABASE_PASSWORD: "supersecret"
  API_KEY: "abc123-def456"
  JWT_SECRET: "my-jwt-secret-key"

Inject ConfigMap as environment variables

envFrom loads every key as an env var, the cleanest option for bulk config. For individual keys, env with configMapKeyRef or secretKeyRef is clearer. Setting optional: false makes a missing key fail at admission instead of booting the app with empty values.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: app
          image: my-app:latest
          envFrom:
            - configMapRef:
                name: app-config
          env:
            - name: DATABASE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: app-secrets
                  key: DATABASE_PASSWORD
            - name: API_KEY
              valueFrom:
                secretKeyRef:
                  name: app-secrets
                  key: API_KEY

Mount ConfigMap as a volume

Mounting writes each key to a file. items selects specific keys and can rename them; omit it and every key becomes a file. Volume-mounted files update automatically when the ConfigMap changes; env vars never do.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: app
          image: my-app:latest
          volumeMounts:
            - name: config-volume
              mountPath: /etc/app/config
              readOnly: true
      volumes:
        - name: config-volume
          configMap:
            name: app-config
            items:
              - key: config.yaml
                path: config.yaml

Mount Secret as a volume

Secrets mount the same way, with one extra knob: defaultMode sets the permissions on the mounted files. 0400 reads as owner-only inside the container, a sane default for credentials.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: app
          image: my-app:latest
          volumeMounts:
            - name: secrets-volume
              mountPath: /etc/app/secrets
              readOnly: true
      volumes:
        - name: secrets-volume
          secret:
            secretName: app-secrets
            defaultMode: 0400  # Owner read-only

Mount a TLS certificate as a volume

The kubernetes.io/tls type requires both tls.crt and tls.key, so a typo in a key name fails fast at pod creation instead of surfacing later as a broken certificate.

apiVersion: v1
kind: Secret
metadata:
  name: tls-secret
type: kubernetes.io/tls
data:
  tls.crt: <base64-encoded-cert>
  tls.key: <base64-encoded-key>
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: app
          image: my-app:latest
          volumeMounts:
            - name: tls
              mountPath: /etc/tls
              readOnly: true
      volumes:
        - name: tls
          secret:
            secretName: tls-secret

Projected volume (combine ConfigMap + Secret)

A projected volume merges several sources (ConfigMaps, Secrets, downward API fields, service-account tokens) into a single mount point. One volumeMounts entry instead of three.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: app
          image: my-app:latest
          volumeMounts:
            - name: combined-config
              mountPath: /etc/app
              readOnly: true
      volumes:
        - name: combined-config
          projected:
            sources:
              - configMap:
                  name: app-config
              - secret:
                  name: app-secrets

Selective env vars from a ConfigMap

For one or two values, configMapKeyRef beats loading the whole object and keeps the env list readable.

spec:
  containers:
    - name: app
      image: my-app:latest
      env:
        - name: LOG_LEVEL
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: LOG_LEVEL
        - name: APP_PORT
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: APP_PORT
        - name: DATABASE_PASSWORD
          valueFrom:
            secretKeyRef:
              name: app-secrets
              key: DATABASE_PASSWORD

Mount a single file with subPath

subPath mounts one file into an existing directory without shadowing the rest of it. The trade-off: the mount resolves once at container start and never receives updates. Mount the whole volume when freshness matters.

spec:
  containers:
    - name: app
      image: my-app:latest
      volumeMounts:
        - name: config-volume
          mountPath: /app/config.yaml
          subPath: config.yaml
          readOnly: true
  volumes:
    - name: config-volume
      configMap:
        name: app-config

Immutable ConfigMaps and Secrets

Mark stable config immutable: true. Kubelet stops watching it for updates, which measurably lowers API-server load on clusters with hundreds of ConfigMaps, and accidental edits become impossible. A change requires a new object.

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
immutable: true
data:
  LOG_LEVEL: "info"
  APP_PORT: "8080"

External Secrets Operator

The External Secrets Operator syncs values from AWS Secrets Manager, HashiCorp Vault, or the GCP/Azure equivalents into a regular Kubernetes Secret on a refreshInterval. Pods see a normal Secret; Git never sees a credential. Working with Docker instead of Kubernetes? The Docker secrets recipe covers the same problem on that runtime.

# ExternalSecret — syncs secrets from AWS Secrets Manager / Vault
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: app-secrets
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: aws-secrets-manager
    kind: ClusterSecretStore
  target:
    name: app-secrets
    creationPolicy: Owner
  data:
    - secretKey: DATABASE_PASSWORD
      remoteRef:
        key: my-app/database
        property: password
    - secretKey: API_KEY
      remoteRef:
        key: my-app/api
        property: key

Sealed Secrets for GitOps

A SealedSecret encrypts the values with the cluster’s public key, so the manifest is safe to commit. Only the controller running in the target cluster can decrypt it. Rotation then becomes a Git workflow; the secrets rotation runbook covers the operational side.

# SealedSecret — encrypted secret safe to store in git
apiVersion: bitnami.com/v1alpha1
kind: SealedSecret
metadata:
  name: app-secrets
spec:
  encryptedData:
    DATABASE_PASSWORD: AgB...
    API_KEY: AgC...
  template:
    metadata:
      name: app-secrets
    type: Opaque

Render config in an init container

When the app expects a file that mixes ConfigMap values with pod-specific data, render it in an init container into an emptyDir shared with the main container. envsubst handles the templating without extra tooling.

spec:
  initContainers:
    - name: config-renderer
      image: my-config-renderer:latest
      env:
        - name: APP_ENV
          value: "production"
      volumeMounts:
        - name: config-template
          mountPath: /templates
        - name: rendered-config
          mountPath: /output
      command:
        - sh
        - -c
        - |
          envsubst < /templates/config.yaml.tpl > /output/config.yaml
  containers:
    - name: app
      image: my-app:latest
      volumeMounts:
        - name: rendered-config
          mountPath: /etc/app/config
          readOnly: true
  volumes:
    - name: config-template
      configMap:
        name: app-config-template
    - name: rendered-config
      emptyDir: {}

Every manifest above is also runnable as a standalone file from the companion repository, including a self-signed demo cert and the apply-and-verify commands.

Explanation

flowchart diagram: CM[ConfigMap

How config updates actually propagate

This is the part that bites people. The three injection paths behave completely differently when the source object changes:

  • Env vars resolve once at container start. Editing the ConfigMap or Secret does nothing until the pod restarts (the most common “why didn’t my config change” question).
  • Volume mounts update automatically: kubelet watches the source object and rewrites the files, typically within ~60 seconds (bounded by the kubelet sync period plus mount propagation). The app still has to re-read the files: the mount doesn’t notify it, which is why frameworks either poll the file or expose a reload endpoint.
  • subPath mounts never update. The path resolves once at start and no watch is established.
  • Immutable objects never update by definition, which is exactly the point of marking them.

Where the mounted files actually live

Volume-mounted config lands in a tmpfs-backed directory: memory-resident, fast to read, and counted against the pod’s memory limit. A 900 KiB ConfigMap inside a 512 Mi pod is a real fraction of the budget. ConfigMaps that exceed the 1 MiB etcd limit fail at admission with a clear error, not a silent truncation.

What actually protects a Secret

A Secret is base64-encoded, not encrypted. Anyone who can run kubectl get secret -o yaml can decode it. The real controls are RBAC on the object, defaultMode on the mounted files, and encryption at rest in etcd via --encryption-provider-config on the API server. For anything you would rotate on suspicion, prefer an external store: etcd backups full of readable Secrets are a common leak path.

Choosing an injection method

MethodUpdates propagate?App reads viaUse when
env / envFromNo — restart requiredgetenv / process.envA few stable values, the simplest case
Volume mountYes (~60 s)File readWhole config files, hot reload
subPath mountNeverFile readOne file into an existing directory
Projected volumeYesFile readConfig and secrets in one mount
External SecretsYes (sync interval)Normal SecretCredentials already in a manager
Sealed SecretsYes (after unseal)Normal SecretGitOps without an external manager

Verify what the pod actually got

kubectl exec deploy/my-app -- env | grep DATABASE
kubectl exec deploy/my-app -- ls -l /etc/app/secrets
kubectl rollout restart deploy/my-app   # force env-var refresh after a config edit

Variants

Using envFrom with a prefix

Prefixes avoid collisions when a ConfigMap and a Secret share key names. APP_DATABASE_HOST next to SECRET_DATABASE_PASSWORD stays readable in env output.

spec:
  containers:
    - name: app
      image: my-app:latest
      envFrom:
        - configMapRef:
            name: app-config
          prefix: APP_
        - secretRef:
            name: app-secrets
          prefix: SECRET_

Hot-reloading a ConfigMap in a volume

The kubelet rewrites mounted files roughly every minute. Apps can watch the file (fsnotify in Go, chokidar in Node.js) and apply the change without a restart, useful for feature flags and log levels but dangerous for anything cached at boot like connection pools.

spec:
  containers:
    - name: app
      image: my-app:latest
      volumeMounts:
        - name: config
          mountPath: /etc/app/config
          readOnly: true
      # The app should watch for file changes
      # e.g., fsnotify in Go, chokidar in Node.js
  volumes:
    - name: config
      configMap:
        name: app-config

Docker config secret for image pulls

imagePullSecrets is how the kubelet authenticates to a private registry at pull time. It’s a Secret like any other, just consumed by the node instead of the container.

apiVersion: v1
kind: Secret
metadata:
  name: registry-credentials
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: <base64-encoded-docker-config>
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  template:
    spec:
      imagePullSecrets:
        - name: registry-credentials
      containers:
        - name: app
          image: private-registry.io/my-app:latest

Best Practices

  • For the decision-making context behind these snippets, see the Kubernetes Config Management guide.
  • ConfigMaps for non-sensitive data, Secrets for sensitive data, never the reverse.
  • readOnly: true on every volume mount. An app should never be able to edit its own config.
  • immutable: true for config that only changes with releases, which is safer and cheaper for the API server.
  • defaultMode: 0400 on secret volumes.
  • External Secrets for production credentials; Sealed Secrets when the source of truth must stay in Git.
  • Never put secrets in a ConfigMap: there’s no encryption at rest on that path.
  • envFrom for bulk loading, env for individual keys.
  • optional: false on critical keys: fail at admission, not at 3 a.m. with an empty password.

Common Mistakes

  • Storing secrets in ConfigMaps: ConfigMaps are plaintext, so anyone with read access sees everything.
  • Expecting env vars to update: they freeze at container start. A ConfigMap edit only reaches the app after a kubectl rollout restart.
  • Using subPath and wondering why files go stale: subPath mounts never receive updates. Mount the whole volume when freshness matters.
  • Treating base64 as encryption: the actual controls are RBAC and etcd encryption at rest; base64 is just transport encoding.
  • Missing keys, silent starts: without optional: false, a typo in the key name boots the pod with an empty value and the failure surfaces somewhere unrelated.
  • Secrets in shell history: kubectl create secret --from-literal=password=... leaves the value in ~/.bash_history. Use --from-file or an external store.

See Also

Frequently Asked Questions

What is the difference between ConfigMap and Secret?

ConfigMaps store non-sensitive data as plaintext. Secrets store sensitive data base64-encoded, with tighter RBAC expectations and optional encryption at rest in etcd. Same mechanics, different trust level.

Are Kubernetes Secrets encrypted?

Not by default — they're base64-encoded. Enable encryption at rest with --encryption-provider-config on the API server, or keep the real values in an external manager and sync them with External Secrets Operator.

How do I update a ConfigMap without restarting pods?

Mount it as a volume: kubelet pushes the change within ~60 seconds and the app re-reads the file. ConfigMaps loaded as env vars always require a pod restart; there's no in-place refresh.

What is a projected volume?

A volume that merges several sources (ConfigMaps, Secrets, downward API fields, service-account tokens) into one directory. It exists to avoid stacking separate volumes and volumeMounts entries for related data.

How do I create a Secret from a file?
kubectl create secret generic app-secrets \
  --from-file=ssl.crt=certs/tls.crt \
  --from-file=ssl.key=certs/tls.key \
  --from-literal=api-key=abc123

Keep in mind --from-literal leaves the value in your shell history, so prefer --from-file or an external store for anything sensitive.