Chuyển đến nội dung chính

Bài 12: Environment Variables, Secrets và Configuration

Quản lý cấu hình với environment variables, .env files, Docker configs, Docker secrets, Vault integration. Best practices bảo mật thông tin nhạy cảm, 12-factor app methodology và configuration management patterns.

🔒 DevSecOps — Bài 12 Bài 12: Environment Variables, Secrets và Configuration

Docker từ Cơ bản đến Nâng cao

Phần 3: Networking, Storage và Compose Nâng cao

xdev.asia

1. Environment Variables trong Docker

Environment variables là cách phổ biến nhất để truyền cấu hình vào containers, tuân theo 12-Factor App methodology.

1.1. Các cách truyền ENV

# 1. Docker run -e flag
docker run -d -e DB_HOST=localhost -e DB_PORT=5432 myapp

2. Từ file

docker run -d --env-file .env myapp

3. Pass từ host environment

export DB_HOST=localhost docker run -d -e DB_HOST myapp # Lấy giá trị từ host

4. Trong Dockerfile

ENV DB_HOST=localhost

1.2. Variable Precedence (thứ tự ưu tiên)

  1. docker run -e hoặc docker compose environment: (cao nhất)

  2. env_file trong docker-compose

  3. ENV trong Dockerfile

  4. Default values trong application code (thấp nhất)

2. .env Files

# .env (auto-loaded by Docker Compose)
NODE_ENV=production
DB_HOST=db
DB_PORT=5432
DB_NAME=myapp
DB_USER=admin
DB_PASSWORD=secretpassword
REDIS_URL=redis://redis:6379
JWT_SECRET=my-jwt-secret-key
# docker-compose.yml
services:
  api:
    image: myapp:latest
    env_file:
      - .env           # Default
      - .env.local      # Local overrides (gitignored)
    environment:
      - NODE_ENV=production  # Override env_file

Best practices cho .env files:

  • .env - Default values, có thể commit vào git

  • .env.local - Local overrides, gitignored

  • .env.production - Production values, deploy qua CI/CD

  • Không bao giờ commit secrets vào git!

3. Docker Secrets

Docker Secrets quản lý sensitive data (passwords, API keys, certificates) an toàn hơn ENV:

3.1. Secrets trong Docker Swarm

# Tạo secret từ file
echo "mysecretpassword" | docker secret create db_password -

Tạo secret từ file

docker secret create ssl_cert ./server.crt

Liệt kê secrets

docker secret ls

Sử dụng trong service

docker service create --name api
--secret db_password
--secret ssl_cert
myapp

Secret available tại /run/secrets/db_password

3.2. Secrets trong Docker Compose

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password

api: image: myapp:latest secrets: - db_password - jwt_secret environment: DB_PASSWORD_FILE: /run/secrets/db_password

secrets: db_password: file: ./secrets/db_password.txt jwt_secret: file: ./secrets/jwt_secret.txt

3.3. Đọc Secrets trong Application

// Node.js - Đọc secret từ file
const fs = require('fs');

function getSecret(name) { try { return fs.readFileSync(/run/secrets/${name}, 'utf8').trim(); } catch (err) { // Fallback to environment variable return process.env[name.toUpperCase()]; } }

const dbPassword = getSecret('db_password');

4. Docker Configs

Docker Configs cho phép lưu trữ non-sensitive configuration data:

services:
  nginx:
    image: nginx:1.27-alpine
    configs:
      - source: nginx_conf
        target: /etc/nginx/nginx.conf

configs: nginx_conf: file: ./nginx/nginx.conf

5. HashiCorp Vault Integration

Vault cung cấp dynamic secrets management:

# docker-compose.yml với Vault
services:
  vault:
    image: hashicorp/vault:1.17
    cap_add:
      - IPC_LOCK
    environment:
      VAULT_DEV_ROOT_TOKEN_ID: myroot
    ports:
      - "8200:8200"

  api:
    image: myapp:latest
    environment:
      VAULT_ADDR: http://vault:8200
      VAULT_TOKEN: myroot

6. 12-Factor App - Configuration

Factor III - Config: "Store config in the environment"

  • Tách configuration khỏi code

  • Cùng image chạy trên dev/staging/production

  • Chỉ thay đổi environment variables

# Cùng image, khác config
services:
  api-dev:
    image: myapp:latest
    environment:
      NODE_ENV: development
      LOG_LEVEL: debug
      DB_HOST: dev-db

  api-prod:
    image: myapp:latest
    environment:
      NODE_ENV: production
      LOG_LEVEL: warn
      DB_HOST: prod-db

7. Configuration Management Patterns

Pattern 1: Config file mount

services:
  api:
    volumes:
      - ./config/production.yml:/app/config/config.yml:ro

Pattern 2: Entrypoint script

#!/bin/sh
# docker-entrypoint.sh

Generate config from environment

envsubst < /app/config.template.yml > /app/config.yml

Read secrets

export DB_PASSWORD=$(cat /run/secrets/db_password)

exec "$@"

COPY docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["node", "server.js"]

8. Security Best Practices

  • Không hardcode secrets trong Dockerfile hoặc docker-compose.yml

  • Không commit .env files với secrets vào git

  • Sử dụng Docker Secrets thay vì ENV cho sensitive data

  • Rotate secrets định kỳ

  • Sử dụng Vault hoặc cloud secret managers cho production

  • Audit access to secrets

9. Tổng kết

Trong bài này, bạn đã nắm được:

  • Environment variables và variable precedence

  • .env files management

  • Docker Secrets cho sensitive data

  • Docker Configs cho non-sensitive config

  • HashiCorp Vault integration

  • 12-Factor App configuration methodology

  • Configuration management patterns và security best practices

Bài tiếp theo sẽ hướng dẫn Docker Security Best Practices.