Using ConfigMaps in Pods
Introduction
ConfigMaps in Kubernetes allow you to decouple configuration artifacts from image content to keep containerized applications portable. This lesson will cover how to create and use ConfigMaps within your Pods.
What is a ConfigMap?
A ConfigMap is an API object used to store non-confidential data in key-value pairs. ConfigMaps can be used to configure application settings, environment variables, command-line arguments, or configuration files.
Creating a ConfigMap
There are several ways to create a ConfigMap:
- From literal values
- From files
- From directories
1. From Literal Values
kubectl create configmap my-config --from-literal=key1=value1 --from-literal=key2=value2
2. From a File
kubectl create configmap my-config --from-file=path/to/config.txt
3. From a Directory
kubectl create configmap my-config --from-file=path/to/directory/
Using ConfigMaps in Pods
Once you've created a ConfigMap, you can use it in your Pods. A ConfigMap can be consumed as:
- Environment Variables
- Command-line Arguments
- Configuration Files in Volumes
Using ConfigMap as Environment Variables
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mycontainer
image: myimage
env:
- name: MY_ENV_VAR
valueFrom:
configMapKeyRef:
name: my-config
key: key1
Using ConfigMap in a Volume
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mycontainer
image: myimage
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: my-config
Best Practices
- Use meaningful names for your ConfigMaps.
- Keep your ConfigMaps small and focused.
- Use versioning in your configuration to manage updates effectively.
- Document the purpose of each key in your ConfigMaps.
FAQ
Can ConfigMaps be updated?
Yes, you can update a ConfigMap using the kubectl apply
command or by recreating it.
What happens if a Pod is using a ConfigMap and the ConfigMap is updated?
The Pod will not automatically get the updated values until it is restarted.
Can ConfigMaps be used in StatefulSets or Deployments?
Yes, ConfigMaps can be used in both StatefulSets and Deployments similarly to how they are used in Pods.