In this lesson, you will learn how to map specific keys from a Kubernetes ConfigMap directly into your container's environment variables so your application can read configuration settings at runtime.
The Problem with Hardcoding
In previous lessons, we learned that ConfigMaps are excellent for decoupling your configuration from your container image. However, simply creating a ConfigMap isn't enough; your application code needs a way to actually "see" those values. While you could mount them as files, mapping them to environment variables is often the standard approach for application frameworks that look for specific system environment keys like DB_HOST or API_KEY.
Mapping ConfigMap Keys to Environment Variables
To inject these values, you use the env field within your container specification. Instead of defining the value directly, you tell Kubernetes to valueFrom a specific configMapKeyRef.
Here is how you configure your Pod specification to pull data from a ConfigMap named app-settings:
apiVersion: v1
kind: Pod
metadata:
name: my-app-pod
spec:
containers:
- name: my-container
image: my-app:1.0
env:
- name: DATABASE_URL
valueFrom:
configMapKeyRef:
name: app-settings
key: db_url
- name: MAX_CONNECTIONS
valueFrom:
configMapKeyRef:
name: app-settings
key: max_conn
In this example, the container will launch with an environment variable named DATABASE_URL populated by the value stored under the db_url key inside the app-settings ConfigMap.
Why use this method?
This approach is powerful because it keeps your container code clean. Your application logic doesn't need to know how to parse Kubernetes files or query the Kubernetes API; it simply reads standard environment variables provided by the operating system. If you need to update the db_url, you simply update the ConfigMap and trigger a rolling update of the Pods. This keeps your configuration fluid and externalized while remaining instantly accessible to your application processes upon startup.
Key Takeaway: By using valueFrom and configMapKeyRef in your Pod specification, you can seamlessly bridge externalized configuration settings into your container's environment variables without changing a single line of application code.