Introduction to ConfigMaps
ConfigMaps in Kubernetes allow you to separate configuration data from the application code. This helps in maintaining cleaner, more modular code and provides an easier way to manage configurations.
Creating and Managing ConfigMaps
To create a ConfigMap, you can use either a YAML file or direct kubectl
commands.
Using YAML
Create a file named my-configmap.yaml
with the following content:
apiVersion: v1
kind: ConfigMap
metadata:
name: my-configmap
data:
key1: value1
key2: value2
Run this command to apply it:
kubectl apply -f my-configmap.yaml
Using kubectl Directly
To create a ConfigMap directly from the command line:
kubectl create configmap my-configmap --from-literal=key1=value1 --from-literal=key2=value2
List ConfigMaps
kubectl get configmaps
Using ConfigMaps in Pods and Applications
You can use ConfigMaps in various ways such as environment variables, command line arguments, or as a file in a volume.
Environment Variable
Create a Pod definition file (pod-using-configmap.yaml
):
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: my-container
image: busybox
envFrom:
- configMapRef:
name: my-configmap
Apply it:
kubectl apply -f pod-using-configmap.yaml
As Volume
In your Pod definition, you can specify the ConfigMap as a volume:
volumes:
- name: config-volume
configMap:
name: my-configmap
Best Practices and Limitations
- Immutable ConfigMaps: Consider making ConfigMaps immutable if they shouldn’t be changed during the lifecycle of the Pod.
- Size Limit: ConfigMaps have a size limit of 1MiB.
ConfigMaps vs Secrets
- Sensitivity: ConfigMaps are not designed to hold sensitive information, unlike Secrets.
- Encryption: Secrets are encrypted at rest, ConfigMaps are not.
Complete Exercise: Using ConfigMap with a Pod
Setup
- Create a ConfigMap:
kubectl create configmap my-configmap --from-literal=key1=value1
Steps
- Create a Pod that uses this ConfigMap as an environment variable.
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: my-container
image: busybox
envFrom:
- configMapRef:
name: my-configmap
- Apply the Pod:
kubectl apply -f pod-using-configmap.yaml
Troubleshooting
- Run
kubectl describe pod mypod
to check for issues. - Make sure the ConfigMap exists:
kubectl get configmaps
Solution
The Pod should be running with environment variables loaded from the ConfigMap. Validate this by running:
kubectl exec -it mypod -- env
You should see key1=value1
among the environment variables.