What is ๐๐จ๐ง๐๐ข๐ ๐ฆ๐๐ฉ and how to use it ?
The most asked Kubernetes Question in interviews:
๐๐จ๐ง๐๐ข๐ ๐๐๐ฉ๐ฌ in Kubernetes are a way to manage configuration data separately from the application code. They allow you to decouple configuration settings from your application's containers, making it easier to update configuration values without changing your application's code.
๐๐ซ๐๐๐ญ๐ ๐ ๐๐จ๐ง๐๐ข๐ ๐๐๐ฉ:
Here's an example of a YAML file to create a ConfigMap:
apiVersion: v1
kind: ConfigMap
metadata:
name: my-config
data:
key1: value1
key2: value2
Apply this YAML file using kubectl apply -f my-configmap.yaml
, and it will create a ConfigMap named my-config
with key-value pairs key1: value1
and key2: value2
.
๐๐๐๐๐ฌ๐ฌ๐ข๐ง๐ ๐๐จ๐ง๐๐ข๐ ๐๐๐ฉ ๐๐๐ญ๐ ๐๐ซ๐จ๐ฆ ๐๐จ๐๐ฌ:
Your application code within the pod can access the ConfigMap data using various methods, such as reading environment variables,command-line arguments, or reading configuration files from the mounted volume.
โ๏ธ ๐๐ฌ ๐๐ง๐ฏ๐ข๐ซ๐จ๐ง๐ฆ๐๐ง๐ญ ๐ฏ๐๐ซ๐ข๐๐๐ฅ๐๐ฌ:
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: my-image
env:
- name: KEY_FROM_CONFIGMAP
valueFrom:
configMapKeyRef:
name: my-config
key: key1
In this example, the value of the environment variable KEY_FROM_CONFIGMAP
is set to the value of key1
from the my-config
ConfigMap.
โ๏ธ ๐๐ฌ ๐๐จ๐ฅ๐ฎ๐ฆ๐๐ฌ:
You can also use ConfigMaps as volumes to inject configuration files into pods. This is useful when you need to provide configuration files to applications. Here's an example:
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: my-image
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: my-config
In this case, the contents of the my-config
ConfigMap will be mounted as files in the /etc/config
directory in the pod.
They help you keep your configuration separate from your application logic, making it easier to manage, update, and maintain your containerized applications.