Today, in the world of application development, it's recommended to separate the configuration from the code. Kubernetes' ConfigMaps
helps us do this.
ConfigMap
ConfigMap
We can use the ConfigMap
for configuration inside a pod in the following ways:
Using commands and arguments inside a container.
Using environment variables for a container
Adding the ConfigMaps
as a file in read-only volume, from where the application can read.
Using the Kubernetes API in the code running inside the container that can read the configmap.
Here, we load the ConfigMaps
values during pod initialization as environment variables.
apiVersion: v1kind: Podmetadata:name: configmap-example-podspec:containers:- name: example-containerimage: alpinecommand: ["sleep", "3600"]env:# Define the environment variable- name: LICENSE # Environment Variable name, can be different from configmap keyvalueFrom:configMapKeyRef:name: example-config # The ConfigMap this value comes from.key: license # The key to fetch.
Line 10: We declare that the following lines in spec
will set the environment of the container.
Line 12: We declare the name of the environment variable.
Line 14: We tell Kubernetes that the value of the environment variable is coming from the ConfigMap
key.
Line 15: We provide the name of the ConfigMap
declared in the previous example.
Line 16: We declare the key whose value is to be assigned to the environment variable.
ConfigMap
as a file in read-only volumeFollowing is an example of how to use values from a ConfigMap
at the time of container initialization:
apiVersion: v1kind: Podmetadata:name: configmap-demo-podspec:containers:- name: demoimage: alpinecommand: ["sleep", "3600"]volumeMounts:- name: configmountPath: "/config"readOnly: truevolumes:- name: configconfigMap:name: example-config
Volumes are set at the pod level, then mounted into containers inside that pod.
Line 15: We provide the name of the config
volume.
Line 17: We assign the name of the ConfigMap
that has to be mounted.
The mounted configuration maps are updated automatically when the value in the `ConfigMap` changes.
ConfigMaps
are a great mechanism to set up configurations separate from code. The configurations are updated automatically and redeployment is not required.
Note: The above does not hold true if the
ConfigMap
is marked asimmutable
.
Free Resources