Kubernetes ConfigMap and Secret YAML example
ConfigMaps hold plain configuration and Secrets hold sensitive values. A Pod can read either one in three ways: every key as environment variables (envFrom), one key as one variable (env with valueFrom), or as files in a mounted volume.
This manifest uses all three so you can compare them. The diagram labels each link with the mechanism. Note that a Secret is only base64-encoded, not encrypted, so keep real values out of files you commit.
What this manifest does
This manifest defines 4 resources in the default namespace: the main thing it runs is 1 Deployment. Let’s walk through it.
Deployment api runs 2 Pods, running myorg/api:2.1.0.
It reads its configuration from ConfigMaps api-config, api-files, and sensitive values from Secret api-db.
Things to know before using it
No topology spread or anti-affinityDeployment api
Deployment "api" has 2 replicas but no spread rules. All Pods could land on one node, a single failure domain. Fix: Add topologySpreadConstraints or podAntiAffinity to spread across zones/nodes.
The full manifest
# One ConfigMap and one Secret, consumed three different ways.
apiVersion: v1
kind: ConfigMap
metadata:
name: api-config
data:
LOG_LEVEL: info
FEATURE_SEARCH: "true"
---
apiVersion: v1
kind: ConfigMap
metadata:
name: api-files
data:
nginx.conf: |
server { listen 8080; }
---
apiVersion: v1
kind: Secret
metadata:
name: api-db
type: Opaque
stringData:
DATABASE_PASSWORD: change-me
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
replicas: 2
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
- name: api
image: myorg/api:2.1.0
ports:
- containerPort: 8080
# 1. Every key in the ConfigMap becomes an environment variable.
envFrom:
- configMapRef:
name: api-config
# 2. One key from the Secret becomes one environment variable.
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: api-db
key: DATABASE_PASSWORD
# 3. A ConfigMap mounted as files.
volumeMounts:
- name: config-files
mountPath: /etc/nginx/conf.d
readOnly: true
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
readinessProbe:
httpGet:
path: /ready
port: 8080
livenessProbe:
httpGet:
path: /healthz
port: 8080
volumes:
- name: config-files
configMap:
name: api-files
Related examples
Stuck on a Kubernetes concept?
Ask anything and get a narrated visual lesson, pitched at your level. Free.
Try an example