☁️ Cloud

ConfigMap

Kubernetes ConfigMap

A Kubernetes resource that stores configuration data. Injects environment variables and configuration files into Pods. Together with Secrets, implements the 12 Factor App.

📖 Detailed Explanation

ConfigMap is an API object in Kubernetes that stores configuration data as key-value pairs. It separates configuration from application code, allowing the same container image to run with different configurations in various environments such as development, staging, and production.

ConfigMap is a core mechanism that implements the third principle of the 12 Factor App, "Store config in the environment." Non-secret configuration data (DB host, feature flags, log level, etc.) is stored in a ConfigMap, while sensitive information (passwords, API keys) is stored in a Secret.

Ways to inject ConfigMap data into a Pod:

The size of a ConfigMap is limited to 1MiB, and if larger configuration is needed, a separate volume or an external configuration server must be used. Also, changes to a ConfigMap are not automatically reflected in existing Pods, so a rolling update strategy is required.

💻 Code Example

# app-config.yaml - 다양한 형태의 ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: production
  labels:
    app: backend
    environment: production
data:
  # 단순 키-값 쌍 (환경변수용)
  DATABASE_HOST: "postgres.production.svc.cluster.local"
  DATABASE_PORT: "5432"
  DATABASE_NAME: "app_production"
  LOG_LEVEL: "info"
  FEATURE_NEW_UI: "true"
  MAX_CONNECTIONS: "100"

  # 설정 파일 전체 (볼륨 마운트용)
  application.yml: |
    spring:
      profiles:
        active: production
      datasource:
        hikari:
          maximum-pool-size: 20
          minimum-idle: 5
          connection-timeout: 30000
      cache:
        type: redis
        redis:
          time-to-live: 3600000

    logging:
      level:
        root: INFO
        com.company.app: DEBUG

    app:
      cors:
        allowed-origins:
          - https://app.company.com
          - https://admin.company.com

  nginx.conf: |
    upstream backend {
        server backend-service:8080;
        keepalive 32;
    }

    server {
        listen 80;
        server_name app.company.com;

        location /api/ {
            proxy_pass http://backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_connect_timeout 30s;
            proxy_read_timeout 60s;
        }

        location /health {
            access_log off;
            return 200 "healthy\n";
        }
    }
---
# 환경별 ConfigMap 분리 예시
apiVersion: v1
kind: ConfigMap
metadata:
  name: feature-flags
  namespace: production
data:
  ENABLE_DARK_MODE: "true"
  ENABLE_BETA_FEATURES: "false"
  MAINTENANCE_MODE: "false"
  A_B_TEST_VARIANT: "control"
# deployment.yaml - ConfigMap 사용 예시
apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend
  namespace: production
spec:
  replicas: 3
  selector:
    matchLabels:
      app: backend
  template:
    metadata:
      labels:
        app: backend
      annotations:
        # ConfigMap 변경 시 자동 롤링 업데이트를 위한 해시
        checksum/config: "{{ include (print $.Template.BasePath \"/configmap.yaml\") . | sha256sum }}"
    spec:
      containers:
      - name: app
        image: company/backend:v1.2.3
        ports:
        - containerPort: 8080

        # 방법 1: 전체 ConfigMap을 환경변수로 주입
        envFrom:
        - configMapRef:
            name: app-config
        - configMapRef:
            name: feature-flags

        # 방법 2: 특정 키만 환경변수로 주입
        env:
        - name: DB_HOST
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: DATABASE_HOST
        - name: DB_PORT
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: DATABASE_PORT
              optional: true  # 키가 없어도 Pod 시작

        # 방법 3: 볼륨 마운트로 설정 파일 주입
        volumeMounts:
        - name: config-volume
          mountPath: /app/config
          readOnly: true
        - name: nginx-config
          mountPath: /etc/nginx/conf.d
          readOnly: true

        resources:
          requests:
            memory: "256Mi"
            cpu: "100m"
          limits:
            memory: "512Mi"
            cpu: "500m"

        readinessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 10
          periodSeconds: 5

      volumes:
      # ConfigMap을 볼륨으로 마운트
      - name: config-volume
        configMap:
          name: app-config
          items:
          - key: application.yml
            path: application.yml
            mode: 0644  # 파일 권한 설정

      - name: nginx-config
        configMap:
          name: app-config
          items:
          - key: nginx.conf
            path: default.conf
# ConfigMap 생성 방법들

# 1. 리터럴 값으로 생성
kubectl create configmap app-settings \
  --from-literal=DATABASE_HOST=postgres.svc \
  --from-literal=DATABASE_PORT=5432 \
  --from-literal=LOG_LEVEL=info \
  -n production

# 2. 파일에서 생성 (파일 이름이 키가 됨)
kubectl create configmap nginx-config \
  --from-file=nginx.conf \
  --from-file=mime.types \
  -n production

# 3. 디렉토리 전체에서 생성
kubectl create configmap app-configs \
  --from-file=./config-dir/ \
  -n production

# 4. env 파일에서 생성
# .env 파일 내용: KEY1=value1\nKEY2=value2
kubectl create configmap env-config \
  --from-env-file=.env \
  -n production

# ConfigMap 조회
kubectl get configmap app-config -n production -o yaml
kubectl describe configmap app-config -n production

# ConfigMap 수정 (에디터로 열기)
kubectl edit configmap app-config -n production

# ConfigMap 업데이트 (파일에서)
kubectl apply -f app-config.yaml

# 특정 키 값만 조회
kubectl get configmap app-config -n production \
  -o jsonpath='{.data.DATABASE_HOST}'

# ConfigMap 삭제
kubectl delete configmap app-config -n production

# Pod에서 ConfigMap 사용 현황 확인
kubectl get pods -n production -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.volumes[*].configMap.name}{"\n"}{end}'

# ConfigMap 변경 후 Deployment 재시작 (롤링 업데이트)
kubectl rollout restart deployment/backend -n production

# Kustomize로 ConfigMap 생성 (권장)
# kustomization.yaml
# configMapGenerator:
# - name: app-config
#   files:
#   - application.yml
#   literals:
#   - LOG_LEVEL=info

🗣️ Say It Like This in Practice

In a deployment pipeline discussion
"We manage per-environment configuration with ConfigMaps. We created separate ConfigMaps for development, staging, and production to keep DB host, log level, and feature flags apart. Since we use the same image and only swap the ConfigMap when deploying, configuration mistakes have dropped significantly."
When asked about Kubernetes experience in an interview
"We use ConfigMaps and Secrets separately. Feature flags and external service URLs go in ConfigMaps, while API keys and DB passwords go in Secrets. Because ConfigMaps are stored in plaintext in etcd, we never put sensitive information in them. We also implemented GitOps with Sealed Secrets and External Secrets."
During a configuration change deployment
"I modified the ConfigMap, but it isn't immediately reflected in existing Pods. With volume mounts, the kubelet syncs periodically, but with environment variables, a Pod restart is required. We put a ConfigMap hash in the Deployment as an annotation so that a rolling update happens automatically when the ConfigMap changes."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌

Storing sensitive information in a ConfigMap

ConfigMaps are stored in plaintext in etcd and can be viewed by anyone via kubectl. Always use a Secret for passwords, API keys, certificates, and the like. Even if access is controlled with RBAC, a ConfigMap is not meant for sensitive information.

❌

Expecting hot reload with environment variables

Environment variables injected via envFrom or env.valueFrom are not reflected in existing Pods even if you modify the ConfigMap. Only the volume mount method is updated through kubelet sync (default 1 minute). A Pod restart is required for a complete update.

✅

Correct approach: Use an Immutable ConfigMap

Setting immutable: true makes the ConfigMap impossible to modify. When changing configuration, it is safer to create a new ConfigMap and update the Deployment. Kustomize's configMapGenerator automatically appends a hash suffix.

🔗 Related Terms

📚 Learn More