Overview
Traditionally, environment variables were defined directly within Pod definition files. For example, a basic Pod configuration might look like this:ConfigMaps store configuration data as key-value pairs. When a Pod is created, this data can be injected either as environment variables or as mounted files, giving your application easy access to the configuration.
- Creating the ConfigMap.
- Injecting the ConfigMap into the Pod.
Creating a ConfigMap
There are two approaches to create ConfigMaps: imperative (command line) and declarative (YAML file).Imperative Approach
The imperative method allows you to create a ConfigMap directly from the command line. For instance, to create a ConfigMap namedapp-config with key-value pairs for APP_COLOR and APP_MODE, run:
app_config.properties), you can create a ConfigMap from that file:
Declarative Approach
For the declarative method, define a ConfigMap in a YAML file and apply it usingkubectl create -f. Below is an example YAML file (config-map.yaml):
When creating multiple ConfigMaps (such as for your application, MySQL, or Redis), use descriptive names. This ensures easier reference within Pod definitions.
Viewing ConfigMaps
To list all available ConfigMaps, you can run:Injecting a ConfigMap into a Pod
After creating a ConfigMap, you can inject the configuration data into a Pod. A common method is using theenvFrom property within the Pod’s container specification, as shown below:
app-config ConfigMap are injected as environment variables into the container.
Alternative Methods for Configuration Injection
There are additional ways to inject configuration data into your Pods:| Method | Description | Example Code Snippet |
|---|---|---|
| Individual Environment Variables | Reference specific keys from the ConfigMap using env and valueFrom. | yaml<br>env:<br> - name: APP_COLOR<br> valueFrom:<br> configMapKeyRef:<br> name: app-config<br> key: APP_COLOR<br> |
| Mounting as a Volume | Mount the ConfigMap as a volume to provide configuration as files. | yaml<br>volumes:<br> - name: app-config-volume<br> configMap:<br> name: app-config<br> |
Now that you understand how to create and inject ConfigMaps, try experimenting with live Kubernetes clusters to practice configuring, viewing, and troubleshooting environment variables.