Cloud Native 34 min read

Mastering Kubernetes ConfigMaps: From Creation to Pod Integration

This comprehensive guide explains how ConfigMaps and Secrets work in Kubernetes, walks through multiple ways to provide configuration to containers—including command‑line arguments, environment variables, and volume mounts—shows how to create ConfigMaps from literals, files, or directories, and demonstrates how to consume them in Pods with env, envFrom, and volume mounts, plus best‑practice tips.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Kubernetes ConfigMaps: From Creation to Pod Integration

ConfigMap and Secret Overview

ConfigMap and Secret are two special types of storage volumes in Kubernetes. ConfigMap objects provide configuration files and other information for containers, while Secret objects store sensitive data such as keys and certificates. Both are stored in objects and mounted as volumes in Pods, achieving decoupling of configuration from container images.

Configuration Methods for Containerized Applications

Each application (e.g., Nginx, Tomcat, MySQL) usually requires custom configuration files. In containers, configuration can be supplied via command‑line arguments, embedding files in the image, environment variables, Docker volumes, Docker config/secret, or Kubernetes ConfigMap/Secret.

Configure via Command‑Line Arguments

Dockerfile supports ENTRYPOINT and CMD. When both exist, CMD arguments are passed to the ENTRYPOINT program. You can also override them with docker run options such as --entrypoint. In Kubernetes, the fields spec.containers.command and spec.containers.args correspond to ENTRYPOINT and CMD respectively. docker run [OPTIONS] IMAGE [COMMAND] [ARG] Example Pod manifest that overrides the default image command:

apiVersion: v1
kind: Pod
metadata:
  name: command-demo
  labels:
    purpose: demonstrate-command
spec:
  containers:
  - name: command-demo-container
    image: busybox
    command: ["httpd"]
    args: ["-f"]
    ports:
    - containerPort: 80

Verify the container process:

kubectl exec -it pods/command-demo -- ps aux
PID   USER   TIME  COMMAND
1 root 0:00 httpd -f
22 root 0:00 ps aux

Configure via Environment Variables

Kubernetes allows you to pass configuration to containers through the env field. Each variable can be defined directly with value or sourced from a ConfigMap or Secret using valueFrom. The syntax is:

env:
- name: VAR_NAME
  value: "value"
- name: VAR_FROM_CM
  valueFrom:
    configMapKeyRef:
      name: my-config
      key: config-key
      optional: false

Example Pod that reads environment variables from a ConfigMap:

apiVersion: v1
kind: Pod
metadata:
  name: env-demo
spec:
  containers:
  - name: env-demo-container
    image: busybox
    command: ["httpd"]
    args: ["-f"]
    env:
    - name: HELLO_WORLD
      value: just a demo
    - name: MY_NODE_NAME
      valueFrom:
        fieldRef:
          fieldPath: spec.nodeName
    - name: MY_NODE_IP
      valueFrom:
        fieldRef:
          fieldPath: status.hostIP
    - name: MY_POD_NAMESPACE
      valueFrom:
        fieldRef:
          fieldPath: metadata.namespace
  restartPolicy: OnFailure

Apply and inspect the variables:

kubectl apply -f env-demo.yaml
kubectl exec -it pods/env-demo -- env | grep HELLO_WORLD
HELLO_WORLD=just a demo
kubectl exec -it pods/env-demo -- env | grep MY_NODE_NAME
MY_NODE_NAME=k8s-node03

Configure via Volumes (ConfigMap as Files)

When configuration data is large (e.g., full configuration files), mounting a ConfigMap as a volume is more appropriate. Each key in the ConfigMap becomes a file whose name is the key and whose content is the value.

Mount the entire ConfigMap:

apiVersion: v1
kind: Pod
metadata:
  name: configmap-volume-pod
spec:
  containers:
  - name: nginx
    image: nginx:latest
    volumeMounts:
    - name: ngx-config
      mountPath: /etc/nginx/conf.d
      readOnly: true
  volumes:
  - name: ngx-config
    configMap:
      name: nginx-config-files

Mount only selected keys using the items field:

apiVersion: v1
kind: Pod
metadata:
  name: configmap-partial-pod
spec:
  containers:
  - name: nginx
    image: nginx:latest
    volumeMounts:
    - name: ngx-config
      mountPath: /etc/nginx/conf.d
      readOnly: true
  volumes:
  - name: ngx-config
    configMap:
      name: nginx-config-files
      items:
      - key: vhost.conf
        path: vhost.conf
        mode: 0644
      - key: gzip.cfg
        path: compression.cfg
        mode: 0644

Mount a single file without overwriting the whole directory using subPath:

apiVersion: v1
kind: Pod
metadata:
  name: configmap-subpath-pod
spec:
  containers:
  - name: nginx
    image: nginx:latest
    volumeMounts:
    - name: ngx-config
      mountPath: /etc/nginx/conf.d/vhost.conf
      subPath: vhost.conf
      readOnly: true
    - name: ngx-html
      mountPath: /usr/share/nginx/html/configmap.html
      subPath: configmap.html
      readOnly: true
  volumes:
  - name: ngx-config
    configMap:
      name: nginx-config-files
  - name: ngx-html
    configMap:
      name: nginx-html-files

Creating ConfigMaps

ConfigMaps can be created directly from literals, files, or directories.

From literals:

kubectl create configmap special-config \
  --from-literal=mysql_ip=172.16.0.3 \
  --from-literal=mysql_port=3306

From a single file:

kubectl create configmap elastic-config \
  --from-file=./elasticsearch.yaml

From a directory (each file becomes a key):

kubectl create configmap nginx-config-files \
  --from-file=./data/nginx/conf.d/

Inspect a ConfigMap:

kubectl get configmap
NAME               DATA   AGE
special-config     2      55s

kubectl describe configmap/special-config
Name:         special-config
Namespace:    default
Data
====
mysql_ip: 172.16.0.3
mysql_port: 3306

Define a ConfigMap with a YAML manifest (useful for version control):

apiVersion: v1
kind: ConfigMap
metadata:
  name: configmap-demo

data:
  log_level: INFO
  log_file: /var/log/test.log

Apply and view:

kubectl apply -f configmap-demo.yaml
kubectl describe configmap configmap-demo
Name:         configmap-demo
Data
====
log_level: INFO
log_file: /var/log/test.log

Injecting ConfigMap Data into Pods

Use env to inject a single key, or envFrom to import all keys at once (optionally with a prefix).

# Single key injection
env:
- name: HTTPD_PORT
  valueFrom:
    configMapKeyRef:
      name: busybox-httpd-config
      key: httpd_port

# Import all keys with a prefix
envFrom:
- prefix: HTCPG_
  configMapRef:
    name: busybox-httpd-config

When a key contains a hyphen, it is converted to an underscore in the environment variable name.

Best Practices and Gotchas

When a ConfigMap is referenced as a volume, the ConfigMap must exist before the Pod starts unless the volume is marked optional: true.

If an environment variable references a non‑existent ConfigMap key, the Pod still starts but an InvalidVariableNames event is recorded.

ConfigMaps are namespace‑scoped; the Pod and the ConfigMap must be in the same namespace.

Kubelet cannot mount a ConfigMap that does not exist in the API server, even when using --manifest-url or --config options.

Full Example: Nginx with ConfigMap Volume

Step 1 – Create configuration files on the host:

# vhost.conf
server {
    listen 80;
    server_name www.k8sops.cn;
    include /etc/nginx/conf.d/*.conf;
    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
    }
}

# gzip.cfg
gzip on;
gzip_min_length 1k;
gzip_buffers 16 64k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_types text/plain application/x-javascript text/css application/xml application/javascript;
gzip_vary on;
gzip_proxied any;

# ngx-status.cfg
location /ngx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

Step 2 – Create a ConfigMap from the directory:

kubectl create configmap nginx-config-files \
  --from-file=./data/nginx/conf.d/

Step 3 – Pod manifest that mounts the ConfigMap:

apiVersion: v1
kind: Pod
metadata:
  name: nginx-config-pod
spec:
  containers:
  - name: nginx
    image: nginx:latest
    volumeMounts:
    - name: ngx-config
      mountPath: /etc/nginx/conf.d
      readOnly: true
  volumes:
  - name: ngx-config
    configMap:
      name: nginx-config-files

Step 4 – Deploy and verify:

kubectl apply -f nginx-config-pod.yaml
kubectl exec -it nginx-config-pod -- ls /etc/nginx/conf.d
vhost.conf  gzip.cfg  ngx-status.cfg
kubectl exec -it nginx-config-pod -- nginx -T
# (output shows the merged configuration)

Step 5 – Access the stub_status endpoint:

kubectl exec -it nginx-config-pod -- curl -s http://127.0.0.1/ngx_status
Active connections: 1
server accepts handled requests
 8 8 8
Reading: 0 Writing: 1 Waiting: 0

Additional Notes

Use subPath when you need to mount a single file from a ConfigMap without overwriting the whole directory.

When mounting a subset of keys, the items field lets you map keys to custom file names and set file permissions.

Remember to delete old Pods after updating a ConfigMap if the Pod does not watch for changes.

Note: When a ConfigMap referenced by a Pod does not exist, the Pod will remain pending until the ConfigMap is created. Pods that do not reference the missing ConfigMap are unaffected.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

KubernetesPodConfigMapEnvironment Variables
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.