Kubernetes: ConfigMaps
A ConfigMap is a place to store configuration outside the container image. Pods read their settings from it, so a setting can change without a new image.
A ConfigMap with two settings
A ConfigMap is plain text. Each key is a setting name and each value is the setting. Nothing here is secret, so it is safe to store this way.
apiVersion: v1
kind: ConfigMap
metadata:
name: web-config
data:
APP_MODE: production
API_HOST: apiRead one setting as an env var
A pod can read one key as an env var. The app code reads the variable as usual. The pod YAML names the ConfigMap and the key.
env:
- name: APP_MODE
valueFrom:
configMapKeyRef:
name: web-config
key: APP_MODERead the ConfigMap back
The ConfigMap lives in the cluster like any other object. You can read it back at any time to check what a pod should see.
kubectl get configmap web-config -o yamlExample
kubectl apply -f web-configmap.yaml
kubectl exec -it web-7d9f4b6c8d-abcde -- printenv APP_MODEKey points
- ConfigMap: a named set of settings that pods can read
- Use a ConfigMap to store settings like a mode, a host name or a feature flag
- Env var: a named value an app reads while it runs.
- Use env vars to give one setting to one container
- Use a mounted file to give a whole config file to a container
- Use a ConfigMap for settings that are safe to read, never for passwords
In this example, the first command creates a ConfigMap called web-config from the file. The second command reads the APP_MODE variable inside the web pod. It shows production, which proves the pod read its setting from the ConfigMap.
Note
Changing a ConfigMap does not restart pods. A pod may need a restart to pick up the new value.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Why should an app read its mode setting from a ConfigMap instead of baking it into the image?