Cloud Native › Kubernetes

Kubernetes ConfigMap, Secret updates, and Native Sidecars

How Kubernetes ConfigMap and Secret mount updates work via ..data symlinks, why subPath stays stale, and how GA Native Sidecar containers fix Job shutdowns.

Kubernetes ConfigMap, Secret updates, and Native Sidecars

Updating a Kubernetes ConfigMap leaves environment variables and subPath mounts stuck on stale values, while running a proxy sidecar in a batch/v1 Job keeps the Job stuck in Running long after the main worker exits. This post verifies all three configuration injection modes, the ..data symlink swap mechanism, Secret base64 encoding pitfalls, and GA Native Sidecar containers on a local kind cluster.

All commands and outputs below were recorded on a local multi-node kind cluster (Kubernetes v1.37.0, kubectl v1.36.1, containerd://2.3.4) using busybox:1.36. Native Sidecar Containers graduated from Alpha (1.28) and Beta (1.29) to GA in Kubernetes 1.33, so they are enabled by default on any 1.33+ cluster.


1. How ConfigMap and Secret injection modes handle updates

On a single Docker host, you separate configuration through .env, env_file, and mounted secret files, as covered in my note on Docker Compose environment precedence and secrets. Kubernetes exposes ConfigMap and Secret data to Pods in three ways, and each behaves differently when the underlying resource changes.

Injection modeManifest fieldUpdates after kubectl patchPropagation delayBest fitAnti-pattern to avoid
Environment variablesenvFrom, env[].valueFromNo (requires Pod restart)N/ABoot-time constants like ports or profilesFeature flags that need live hot reload
Directory volume mountvolumeMounts (mountPath)Yes (..data symlink swap)kubelet sync period (~60s typical)Config files or certificates reloaded by the appMounting over a directory that holds other files baked into the image
Single-file subPath mountvolumeMounts + subPathNo (pinned to old inode)N/AInjecting one static file without hiding sibling filesExpecting live reloads on a subPath-mounted config file

When not to rely on live volume updates: Directory mounts update asynchronously across nodes based on kubelet’s syncFrequency (1 minute by default) plus cache TTL. If every Pod must switch to a new config version together—or if you want clean rollout history and rollbacks—skip live volume mutation. Create a new immutable: true ConfigMap with a versioned name and trigger a standard Deployment rolling update instead.


The difference between the three modes comes down to the Linux process model and kubelet’s AtomicWriter:

  • Environment variables (envFrom/valueFrom): A POSIX process copies its environment block at startup. Patching a ConfigMap in the API server never mutates the environment memory of a running process.
  • Directory volume mounts: kubelet writes keys into a hidden timestamped directory (..YYYY_MM_DD_...), points a ..data symlink at it, and links each key file through ..data (greeting -> ..data/greeting). On an update, kubelet creates a new timestamped directory, atomically renames ..data to point there, and removes the old directory.
  • subPath mounts: The container runtime bind-mounts a single file inode directly into the container path. When kubelet deletes the old timestamped directory, the bind mount still holds the unlinked inode, so reads keep returning the original v1 bytes.
flowchart TD
    CM["Patch ConfigMap (v1 -> v2)"] --> K["kubelet sync period triggers"]
    K --> NEW["Create new timestamp directory"]
    NEW --> SWAP["Atomically swap ..data symlink"]
    SWAP --> DIR["/etc/config/greeting -> ..data/greeting (reads v2)"]
    SWAP --> SUB["/etc/sub/greeting bind mount (old inode, stays v1)"]

To compare all three side by side, create the dedicated namespace (kubectl create namespace lab-d4-config) and mount app-config into one Pod (config-demo) via envFrom, valueFrom, a directory mount (/etc/config), and a subPath mount (/etc/sub/greeting).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 01-config-secret.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: lab-d4-config
data:
  greeting: "v1"
  mode: "standard"
---
apiVersion: v1
kind: Secret
metadata:
  name: app-secret
  namespace: lab-d4-config
type: Opaque
stringData:
  api_key: "dummy-key-v1"
---
apiVersion: v1
kind: Pod
metadata:
  name: config-demo
  namespace: lab-d4-config
spec:
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c", "sleep 3600"]
      envFrom:
        - configMapRef:
            name: app-config
      env:
        - name: GREETING_ENV
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: greeting
        - name: API_KEY
          valueFrom:
            secretKeyRef:
              name: app-secret
              key: api_key
      volumeMounts:
        - name: config-vol
          mountPath: /etc/config
          readOnly: true
        - name: config-vol
          mountPath: /etc/sub/greeting
          subPath: greeting
          readOnly: true
        - name: secret-vol
          mountPath: /etc/secret
          readOnly: true
  volumes:
    - name: config-vol
      configMap:
        name: app-config
    - name: secret-vol
      secret:
        secretName: app-secret

Right after the Pod becomes Ready, all three injection methods read v1:

1
2
3
4
5
6
7
kubectl -n lab-d4-config exec config-demo -- sh -c '
  echo "envFrom greeting=$greeting"
  echo "valueFrom GREETING_ENV=$GREETING_ENV"
  echo "dir-mount /etc/config/greeting=$(cat /etc/config/greeting)"
  echo "subPath   /etc/sub/greeting=$(cat /etc/sub/greeting)"
  ls -la /etc/config /etc/sub
'
1
2
3
4
5
6
7
8
9
10
11
envFrom greeting=v1
valueFrom GREETING_ENV=v1
dir-mount /etc/config/greeting=v1
subPath   /etc/sub/greeting=v1
--- ls -la /etc/config ---
drwxr-xr-x    2 root     root          4096 Dec  5 14:58 ..2026_12_05_14_58_20.1211798184
lrwxrwxrwx    1 root     root            32 Dec  5 14:58 ..data -> ..2026_12_05_14_58_20.1211798184
lrwxrwxrwx    1 root     root            15 Dec  5 14:58 greeting -> ..data/greeting
lrwxrwxrwx    1 root     root            11 Dec  5 14:58 mode -> ..data/mode
--- ls -la /etc/sub ---
-rw-r--r--    1 root     root             2 Dec  5 14:58 greeting

Next, patch greeting to v2 and poll every 2 seconds until kubelet syncs the volume:

1
2
kubectl -n lab-d4-config patch configmap app-config \
  --type merge -p '{"data":{"greeting":"v2"}}'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Patch time: 2026-12-05T14:58:40Z
configmap/app-config patched
Detected /etc/config/greeting=v2 at +56s (2026-12-05T14:59:36Z)
=== After patch (updated=1) ===
envFrom greeting=v1
valueFrom GREETING_ENV=v1
dir-mount /etc/config/greeting=v2
subPath   /etc/sub/greeting=v1
--- ls -la /etc/config ---
drwxr-xr-x    2 root     root          4096 Dec  5 14:59 ..2026_12_05_14_59_35.3727926152
lrwxrwxrwx    1 root     root            32 Dec  5 14:59 ..data -> ..2026_12_05_14_59_35.3727926152
lrwxrwxrwx    1 root     root            15 Dec  5 14:58 greeting -> ..data/greeting
lrwxrwxrwx    1 root     root            11 Dec  5 14:58 mode -> ..data/mode
--- ls -la /etc/sub ---
-rw-r--r--    0 root     root             2 Dec  5 14:58 greeting

Three details stand out from the output:

  1. +56 seconds after the patch, only /etc/config/greeting updated to v2. Both environment variables and /etc/sub/greeting stayed at v1.
  2. Inside /etc/config, greeting -> ..data/greeting kept its original 14:58 timestamp while ..data atomically switched to ..2026_12_05_14_59_35.3727926152.
  3. /etc/sub/greeting is a regular file rather than a symlink, and its link count dropped from 1 to 0. kubelet unlinked the old timestamped directory, but the bind mount kept the unlinked inode alive with v1.

3. Secret base64 encoding limits and operational security

Despite the name, a default Opaque Secret is base64-encoded, not encrypted. Anyone who can read app-secret decodes api_key in one command:

1
2
kubectl -n lab-d4-config get secret app-secret -o yaml
echo ZHVtbXkta2V5LXYx | base64 -d
1
2
3
4
data:
  api_key: ZHVtbXkta2V5LXYx
# base64 -d output:
dummy-key-v1

The test also exposed a common trap with kubectl apply: when a manifest uses stringData, kubectl apply copies the raw plaintext into metadata.annotations["kubectl.kubernetes.io/last-applied-configuration"]. Even though Kubernetes converts stringData into base64 under data, the plaintext remains visible in the annotation.

The operational security patterns below were not configured or measured in this kind experiment. They reflect official Kubernetes documentation and standard production practice.

  • Encryption at rest in etcd: The official docs recommend configuring EncryptionConfiguration on the API server with an external KMS v2 provider so secrets aren’t stored as plain base64 on disk.
  • Least-privilege RBAC: Restrict get, list, and watch verbs on secrets to the minimum set of ServiceAccounts and cluster roles.
  • External secret managers and rollout triggers: Teams typically keep raw secrets out of Git by syncing from Vault or cloud secret managers via External Secrets Operator or the Secrets Store CSI Driver. When Pods consume secrets through env vars or subPath, tools like Stakater Reloader or Helm sha256sum pod-template annotations trigger clean rollouts on change.

4. Reproducing the legacy sidecar Job shutdown deadlock

Before Native Sidecars, teams placed log shippers, TLS proxies, and mesh proxies inside spec.containers alongside the main app. That creates two recurring failures:

  1. No startup ordering: Containers in spec.containers start in parallel. The main app can try to connect before the proxy finishes initializing.
  2. Stuck batch/v1 Job completions: A Job only reaches Complete when every regular container in the Pod exits. If batch-worker finishes with exit 0 while proxy-sidecar stays alive, the Job sits in Running forever.

Here is a minimal legacy-sidecar-job that reproduces the deadlock:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 02-legacy-sidecar-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: legacy-sidecar-job
  namespace: lab-d4-config
spec:
  backoffLimit: 0
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: batch-worker
          image: busybox:1.36
          command:
            - sh
            - -c
            - |
              echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') [worker] started"
              sleep 3
              echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') [worker] finished with exit 0"
        - name: proxy-sidecar
          image: busybox:1.36
          command:
            - sh
            - -c
            - |
              trap 'echo "$(date -u "+%Y-%m-%dT%H:%M:%SZ") [sidecar] SIGTERM received"; exit 0' TERM
              echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') [sidecar] started (legacy container)"
              sleep 3600 &
              wait $!

Ten seconds after applying the Job, batch-worker has exited cleanly, yet the Job is still Running:

1
2
3
4
5
6
7
8
9
NAME                 STATUS    COMPLETIONS   DURATION   AGE   CONTAINERS                   IMAGES
legacy-sidecar-job   Running   0/1           10s        10s   batch-worker,proxy-sidecar   busybox:1.36,busybox:1.36

NAME                       READY   STATUS     RESTARTS   AGE   IP               NODE
legacy-sidecar-job-lwg54   1/2     NotReady   0          10s   192.168.25.145   k8s-lab2-worker

--- containerStatuses ---
batch-worker:  ready=false, state={"terminated":{"exitCode":0,"finishedAt":"2026-12-05T14:58:53Z","reason":"Completed","startedAt":"2026-12-05T14:58:50Z"}}
proxy-sidecar: ready=true,  state={"running":{"startedAt":"2026-12-05T14:58:50Z"}}

Historically, working around this meant writing custom glue—dropping a marker file into a shared emptyDir or calling a local shutdown endpoint on the sidecar from the worker’s exit hook.


5. Verifying GA Native Sidecar startup order and clean shutdown

Native Sidecar Containers (GA in Kubernetes 1.33) solve both problems at the Pod spec level by placing the sidecar in spec.initContainers with restartPolicy: Always. kubelet enforces three lifecycle rules:

  • Ordered startup: Native sidecars launch in declaration order and block subsequent init or main containers until they pass their startupProbe (if defined) and reach started.
  • Independent restarts: Unlike one-shot init containers, a crashing native sidecar restarts on its own even when the Pod’s restartPolicy is Never.
  • Reverse-order shutdown: Once every main container terminates, kubelet sends SIGTERM to native sidecars in reverse order so Job Pods finish cleanly. (For probe semantics and SIGTERM grace periods, see my note on Kubernetes probes, resource limits, and preStop.)
sequenceDiagram
    participant K as kubelet
    participant S as proxy-sidecar (Native)
    participant W as batch-worker (Main)
    K->>S: 14:59:00Z Start (3s warm-up)
    S-->>K: 14:59:03Z startupProbe passes
    K->>W: 14:59:04Z Start main container
    W-->>K: 14:59:07Z Exit 0
    K->>S: 14:59:07Z Send SIGTERM
    S-->>K: 14:59:07Z Exit 0 (Job Complete)

Moving proxy-sidecar into initContainers with restartPolicy: Always and a startupProbe gives this manifest:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 03-native-sidecar-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: native-sidecar-job
  namespace: lab-d4-config
spec:
  backoffLimit: 0
  template:
    spec:
      restartPolicy: Never
      initContainers:
        - name: proxy-sidecar
          image: busybox:1.36
          restartPolicy: Always
          command:
            - sh
            - -c
            - |
              trap 'echo "$(date -u "+%Y-%m-%dT%H:%M:%SZ") [sidecar] SIGTERM received, exiting cleanly"; exit 0' TERM
              echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') [sidecar] starting warm-up (3s)..."
              sleep 3
              touch /tmp/proxy-ready
              echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') [sidecar] ready (/tmp/proxy-ready created)"
              sleep 3600 &
              wait $!
          startupProbe:
            exec:
              command: ["test", "-f", "/tmp/proxy-ready"]
            periodSeconds: 1
            failureThreshold: 15
      containers:
        - name: batch-worker
          image: busybox:1.36
          command:
            - sh
            - -c
            - |
              echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') [worker] started (after sidecar startupProbe passed)"
              sleep 3
              echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') [worker] finished with exit 0"

Waiting for condition=Complete and inspecting both logs confirms the exact sequence:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
job.batch/native-sidecar-job condition met

NAME                 STATUS     COMPLETIONS   DURATION   AGE   CONTAINERS     IMAGES
native-sidecar-job   Complete   1/1           10s        10s   batch-worker   busybox:1.36

NAME                       READY   STATUS      RESTARTS   AGE   IP               NODE
native-sidecar-job-n74cb   0/2     Completed   0          10s   192.168.25.146   k8s-lab2-worker

--- logs (proxy-sidecar) ---
2026-12-05T14:59:00Z [sidecar] starting warm-up (3s)...
2026-12-05T14:59:03Z [sidecar] ready (/tmp/proxy-ready created)
2026-12-05T14:59:07Z [sidecar] SIGTERM received, exiting cleanly

--- logs (batch-worker) ---
2026-12-05T14:59:04Z [worker] started (after sidecar startupProbe passed)
2026-12-05T14:59:07Z [worker] finished with exit 0

proxy-sidecar started at 14:59:00Z and passed its startupProbe at 14:59:03Z. Only then did batch-worker start at 14:59:04Z. When batch-worker exited 0 at 14:59:07Z, kubelet delivered SIGTERM to proxy-sidecar within the same second, and the Job finished Complete (1/1) in 10s without any custom shutdown scripts.

BehaviorLegacy containers sidecarNative Sidecar (initContainers + restartPolicy: Always)
Startup order vs. main appNot guaranteed (parallel start)Guaranteed after startupProbe passes
Behavior after Job worker exitsKeeps running; Job stays RunningReceives SIGTERM automatically; Job reaches Complete
Pod termination orderParallel SIGTERM (risk of dropped logs)Main containers stop first, sidecar stops after
Kubernetes supportAll versions1.29 Beta (on by default), 1.33+ GA

When not to use Native Sidecars: Keep one-shot setup steps (schema migrations, config downloads) as regular initContainers without restartPolicy: Always—they must exit before the app starts. Also avoid setting initContainers[].restartPolicy on clusters older than 1.29 (or where the SidecarContainers gate is disabled), as the API server will reject the manifest.


6. Production pitfalls and checklist

Three common production pitfalls

  1. App ignores refreshed volume files: Even when kubelet swaps ..data, an application that reads its config once at boot won’t pick up the change. If you add an inotify file watcher, watch the directory or ..data symlink rather than a single file inode.
  2. Plaintext stringData left in last-applied-configuration: Deploying Secrets with kubectl apply and stringData stores plaintext in the annotation. Use external secret sync controllers or restrict Secret RBAC tightly.
  3. Native Sidecar ignoring SIGTERM: If a sidecar swallows SIGTERM (for example, a shell script without exec or trap), Job completion stalls for the full terminationGracePeriodSeconds (30s default) before kubelet sends SIGKILL.

Run through these five checks before shipping configuration or sidecar changes:

  • Use directory volumeMounts (not subPath) for any config file that needs runtime updates.
  • Prefer immutable: true ConfigMaps with Deployment rolling updates when all Pods must switch versions together.
  • Lock down Secret RBAC and avoid leaving stringData plaintext in Git or last-applied-configuration annotations.
  • Move proxy and log-collector sidecars (especially in Job and CronJob workloads) on Kubernetes 1.33+ to initContainers with restartPolicy: Always and a startupProbe.
  • Verify in logs that each Native Sidecar traps SIGTERM, flushes buffers, and exits 0 promptly.

References

A ConfigMap is an API object used to store non-confidential data in key-value pairs. Pods can consume ConfigMaps as environment variables, command-line arguments, or as configuration files in a volume. A ConfigMap allows you to decouple environment-specific configuration from your container images, so that your applications are easily portable.
A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key. Such information might otherwise be put in a Pod specification or in a container image. Using a Secret means that you don't need to include confidential data in your application code.
Feature state: Stable since Kubernetes v1.33 More information about this feature This is a stable feature in Kubernetes, and has been since version v1.33. It was first available in the v1.28 release. You can no longer disable or opt out of this feature or behavior (it is locked); if you explicitly set a value for the associated feature gate SidecarContainers, Kubernetes ignores it but does not report any error.
This post is licensed under CC BY 4.0 by the author.