Deploying Stateful Microservices: Persisting Data in Kubernetes
Consuming ConfigMaps
We previously created a ConfigMap named postgres-config that contains the environment variables required to configure PostgreSQL. Now, we will see how to consume it.
When creating a Pod, we can specify the ConfigMap in the Pod specification. Kubernetes will then inject the ConfigMap data into the Pod as environment variables or as files in a volume.
This is how to define this in YAML:
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres
namespace: postgres
spec:
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:18
# Tell Kubernetes to always pull the image
# even if it is already present on the node
imagePullPolicy: Always
ports:
- containerPort: 5432
envFrom:
- configMapRef:
name: postgres-config
The envFrom field in the container specification tells Kubernetes to inject all the key-value pairs from the ConfigMap named postgres-config as environment variables in the container. Our ConfigMap should now be consumed by the PostgreSQL container. To add more variables, we can simply update the ConfigMap without needing to modify the Deployment—only restart its Pods (kubectl rollout restart deployment postgres -n postgres).
An alternative way to add environment variables is to use the env field in the container specification. This way, we can specify each environment variable individually. Here is an example:
apiVersionCloud-Native Microservices With Kubernetes - 2nd Edition
A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in KubernetesEnroll now to unlock all content and receive all future updates for free.
