Pod with Secrets as Environment Variables

Configure a Kubernetes pod to inject sensitive values (database passwords, API keys) from Kubernetes Secrets as environment variables instead of hardcoding them in the manifest.

Security

Detailed Explanation

Using Kubernetes Secrets

Hardcoding passwords and API keys in your Deployment manifests is a security risk. Kubernetes Secrets provide a way to store sensitive data separately and inject it into pods as environment variables or mounted files.

Key Configuration

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-server
  labels:
    app: "api-server"
spec:
  replicas: 2
  template:
    spec:
      containers:
        - name: api
          image: my-api:latest
          ports:
            - name: http
              containerPort: 8080
          env:
            - name: DATABASE_URL
              value: "postgres://$(DB_USER):$(DB_PASS)@postgres:5432/mydb"
          volumeMounts:
            - name: secrets
              mountPath: /etc/secrets
              readOnly: true
      volumes:
        - name: secrets
          secret:
            secretName: api-credentials

Creating Secrets

kubectl create secret generic api-credentials \
  --from-literal=DB_USER=admin \
  --from-literal=DB_PASS=supersecret \
  --from-literal=API_KEY=sk-abc123

Environment Variables vs Volume Mounts

Method Pros Cons
Env vars Simple, framework-native Visible in pod describe, no auto-update
Volume mounts Auto-updates, multiple files Requires file reading in app

Security Best Practices

  • RBAC: Restrict who can read Secrets with Role/ClusterRole bindings
  • Encryption at rest: Enable etcd encryption for secrets in your cluster
  • External secrets: Consider tools like External Secrets Operator, Vault, or Sealed Secrets for production
  • Avoid logging secrets: Ensure your application does not log environment variables at startup
  • Rotation: Volume-mounted secrets update automatically when the Secret is updated; environment variables require a pod restart

Use Case

Securely injecting database credentials, API keys, and other sensitive configuration into Kubernetes pods without hardcoding them in deployment manifests or container images.

Try It — K8s Pod Spec Builder

Open full tool