How to Mount ConfigMap as Volume in Kubernetes
To mount a
ConfigMap as a volume in Kubernetes, define a volume with configMap in your pod spec and then mount it inside a container using volumeMounts. This makes the ConfigMap data available as files inside the container.Syntax
Mounting a ConfigMap as a volume involves two main parts in the pod spec:
- volumes: Define a volume with
configMapspecifying the ConfigMap name. - containers.volumeMounts: Mount the volume inside the container at a desired path.
yaml
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: example-container
image: nginx
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: example-configmapExample
This example shows a pod that mounts a ConfigMap named example-configmap as a volume at /etc/config. The ConfigMap's keys become files inside that directory.
yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: example-configmap
data:
app.properties: |
color=blue
size=large
---
apiVersion: v1
kind: Pod
metadata:
name: configmap-volume-pod
spec:
containers:
- name: app-container
image: busybox
command: ["sleep", "3600"]
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: example-configmapOutput
kubectl get pod configmap-volume-pod
NAME READY STATUS RESTARTS AGE
configmap-volume-pod 1/1 Running 0 10s
kubectl exec configmap-volume-pod -- cat /etc/config/app.properties
color=blue
size=large
Common Pitfalls
Common mistakes when mounting ConfigMaps as volumes include:
- Using a wrong ConfigMap name in the volume spec, causing mount failure.
- Not specifying
volumeMountsin the container, so the volume is not accessible. - Mounting at a path that conflicts with existing container files.
- Expecting ConfigMap keys as environment variables instead of files (different method).
yaml
apiVersion: v1
kind: Pod
metadata:
name: wrong-pod
spec:
containers:
- name: app
image: busybox
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: wrong-configmap # Incorrect name causes mount failureQuick Reference
| Field | Description |
|---|---|
| volumes[].configMap.name | Name of the ConfigMap to mount |
| containers[].volumeMounts[].name | Name of the volume to mount |
| containers[].volumeMounts[].mountPath | Path inside container where ConfigMap files appear |
| ConfigMap keys | Become files inside the mounted directory |
Key Takeaways
Define a volume with configMap and mount it inside the container using volumeMounts.
ConfigMap keys appear as files in the mounted directory inside the container.
Ensure the ConfigMap name matches exactly in the volume spec to avoid mount errors.
Mount paths should not overwrite important container files or directories.
Mounting ConfigMaps as volumes is different from using them as environment variables.