Kubernetes ConfigMap Best Practices

The third factor of the twelve-factor app is to store your application’s configuration in the environment.

How to use ConfigMaps

In Kubernetes, you can have deployments that have their environment variables defined explicitly:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-container
        image: my-image:latest
        env:
        - name: APP_ENV
          value: production
        - name: DB_HOST
          value: db.example.com
        - name: DB_PORT
          value: "5432"

Another way of doing this is to leverage ConfigMaps:

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-config
data:
  APP_ENV: production
  DB_HOST: db.example.com
  DB_PORT: "5432"

Then you can refer to them in your deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-container
        image: my-image:latest
        envFrom:
        - configMapRef:
            name: my-config

The three key values in the ConfigMap will then be set as environment variables in the deployment’s pods.

Best Practices

Use ConfigMaps for key-value configuration that is separate from your application code. You should logically organize them so that you can reduce duplication between any applications that depend on the same configuration.

In general, I would recommend separating any shared ConfigMaps from any single application/service. For example, if services A and B depend on a common ConfigMap, don’t have either service A or B create it.

Know that pods will not automatically pick up the changes from ConfigMap unless they’re restarted or the application is designed to reload the configuration dynamically.

Sensitive data should go into Secrets, which are essentially ConfigMaps but for secrets.

Version your ConfigMaps so that you can roll them back independently of your application code.

Be aware and know the limitations of ConfigMaps. The total size of a ConfigMap can’t exceed 1 MB. The maximum size of a single key-value can’t exceed 1 MB. You can have unlimited key-value pairs in a ConfigMap up to that 1 Mb limit.


Master GitHub Actions with a Senior Infrastructure Engineer

As a senior staff infrastructure engineer, I share exclusive, behind-the-scenes insights that you won't find anywhere else. Get the strategies and techniques I've used to save companies $500k in CI costs and transform teams with GitOps best practices—delivered straight to your inbox.

Not sure yet? Check out the archive.

Unsubscribe at any time.