In this lesson, you will learn how to decouple your sensitive credentials and application settings from your container images to maintain a clean, reusable architecture within StatefulSets.
When running stateful applications—like a database cluster—you often need to provide connection strings, API keys, or custom configuration files. Baking these directly into your Docker image is a security risk and limits your agility, as you’d have to rebuild the image every time a password changes. Instead, we use Kubernetes ConfigMaps and Secrets.
Keeping Configuration Dynamic
A ConfigMap stores non-sensitive configuration data (like db-settings.conf), while a Secret stores sensitive data (like db-password). When you inject these into a StatefulSet, Kubernetes mounts them as files into the pod’s filesystem or exposes them as environment variables. Because your StatefulSet pods have stable, predictable identities (like db-0, db-1), you can inject configuration specific to those instances if needed, or share a common configuration across the entire cluster.
Practical Implementation
To use these in your StatefulSet, you reference them within the spec.template.spec section:
spec:
template:
spec:
containers:
- name: database
image: my-db-image:1.0
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-creds
key: password
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: app-config
By mounting these as volumes, the files appear inside the container at runtime. If you update the ConfigMap or Secret, Kubernetes handles the propagation. This approach ensures your container image remains immutable and portable, while your environment-specific configuration remains externalized and secure. You aren't changing the software; you are simply providing it with the unique "credentials" it needs to perform its job in a specific cluster.
Key Takeaway: By using ConfigMaps and Secrets, you ensure your StatefulSet pods remain generic and portable while securely injecting the dynamic, environment-specific data they need to function.