# ConfigMap

## [About](https://kubernetes.io/docs/reference/kubernetes-api/config-and-storage-resources/config-map-v1/)

A **ConfigMap** is a Kubernetes object that stores **non-confidential configuration data** in **key-value pairs**.

It lets you decouple environment-specific config (like database URLs, feature flags, API endpoints) from your container images and Pods.

{% hint style="danger" %}
ConfigMaps are for **non-sensitive** data.

For **secrets** (passwords, API keys, TLS certs), use **Secrets**, not ConfigMaps.
{% endhint %}

{% hint style="warning" %}
**ConfigMaps can be updated, but Pods don’t automatically reload** the new config unless:

* The app watches the config files, OR
* You restart the Pods.
  {% endhint %}

## Commands

Create ConfigMap from literal values:

```bash
kubectl create configmap <configmap-name> \
  --from-literal=node_env=production \
  --from-literal=port=8000
```

Create ConfigMap from a file:

```bash
kubectl create configmap <configmap-name> --from-file=.env
```

## Example

{% code title="configmap-env.yaml" %}

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: myconfig
data:
  db_host: mysql.example.com
  db_port: "3306"
  feature_flag: "true"
```

{% endcode %}

How to use in Deployment example 1 (Individual env variables):

{% code title="deployment.yaml" %}

```yaml
...
spec:
  template:
    ...
    spec:
      containers:
        - name: myapp-container
          image: nginx:1.25
          ports:
            - containerPort: 80
          env:
            - name: DB_HOST
              valueFrom:
                configMapKeyRef:
                  name: myconfig   # name of the ConfigMap
                  key: db_host
```

{% endcode %}

How to use in Deployment example 2 (Whole env file):

{% code title="deployment.yaml" %}

```yaml
...
spec:
  template:
    ...
    spec:
      containers:
        - name: myapp-container
          image: nginx:1.25
          ports:
            - containerPort: 80
          envFrom:
            - configMapRef:
              name: myconfig   # name of the ConfigMap
```

{% endcode %}

How to use in Deployment example 3 (Injected as a volume):

{% code title="deployment.yaml" %}

```yaml
...
spec:
  template:
    ...
    spec:
      containers:
        - name: myapp-container
          image: nginx:1.25
          ports:
            - containerPort: 80
          volumeMounts:
            - mountPath: /etc/config
              name: config-volume
      volumes:
        - name: config-volume
          configMap:
            name: myconfig
```

{% endcode %}
