Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 19: Biến môi trường và secret trong Docker Compose

Cuối bài trước có một điều đã thấy suốt mấy bài: mật khẩu doi-mat-khau-nay nằm rải rác trong compose.yaml và compose.override.yaml, hai file được commit vào git. Bài này mình sẽ giới thiệu với mọi người về biến môi trường và secret trong Docker Compose: interpolation ${VAR}, file .env và --env-file, env_file, secrets:, rồi dùng chúng để đưa mọi mật khẩu của TaskFlow ra khỏi file Compose.

Output trong bài là output thật trên Docker Engine 29.10 với Docker Compose 5.8, máy linux/arm64 (không giả lập, như bài 18), phần lược bớt là # .... Cần các image postgres:18-alpine, redis:8-alpine, taskflow-api:0.53.0, alpine:3.24 từ các bài trước và mã TaskFlow ở ~/taskflow.

1. Mật khẩu đang nằm ở đâu?

Tìm chuỗi mật khẩu trong hai file của bài 18:

cd ~/taskflow-docker/examples
grep -n doi-mat-khau-nay 18-dev/compose.yaml 18-dev/compose.override.yaml
# 18-dev/compose.yaml:12:      POSTGRES_PASSWORD: doi-mat-khau-nay
# 18-dev/compose.yaml:26:    command: ["redis-server", "--appendonly", "yes", "--requirepass", "doi-mat-khau-nay"]
# 18-dev/compose.yaml:28:      REDISCLI_AUTH: doi-mat-khau-nay # mật khẩu cho redis-cli của healthcheck
# 18-dev/compose.yaml:44:      DATABASE_URL: postgres://taskflow:doi-mat-khau-nay@db:5432/taskflow?sslmode=disable
# 18-dev/compose.yaml:59:      TASKFLOW_JWT_SECRET: doi-mat-khau-nay-doi-mat-khau-nay
# 18-dev/compose.yaml:60:      DATABASE_URL: postgres://taskflow:doi-mat-khau-nay@db:5432/taskflow?sslmode=disable
# 18-dev/compose.yaml:61:      TASKFLOW_REDIS_URL: redis://:doi-mat-khau-nay@redis:6379/0
# 18-dev/compose.override.yaml:32:      PGPASSWORD: doi-mat-khau-nay

Tám dòng cho ba secret: mật khẩu PostgreSQL (4 chỗ), mật khẩu Redis (3 chỗ) và JWT secret. Ai đọc được repo là có mật khẩu, còn đổi mật khẩu thì phải sửa nhiều chỗ, sót một chỗ là stack hỏng. Mình thử từng công cụ của Compose trên một file nhỏ trong /tmp/thu19 trước, rồi mới áp dụng cho TaskFlow ở phần 5. Thư mục examples/19-secrets trong repo của series đã là bản cuối của bài (không còn mật khẩu). Nếu tự gõ lại từ đầu thì tạo nó bằng mkdir -p 19-secrets, chép hai file của 18-dev sang rồi sửa theo phần 5.

2. Interpolation trong compose.yaml.

Interpolation là việc Compose thay ${VAR} trong file bằng giá trị của biến, ngay lúc đọc file. Tạo thư mục thử (mkdir -p /tmp/thu19 && cd /tmp/thu19) và file compose.yaml trong đó, một service chỉ in các biến APP_*:

services:
  app:
    image: alpine:3.24
    command: ["sh", "-c", "env | grep ^APP_ | sort"]
    environment:
      APP_TAG: ${TAG:-mac-dinh}
      APP_LEVEL: ${LOG_LEVEL}
      APP_SECRET: ${APP_SECRET:?chưa đặt APP_SECRET}
      APP_HOME: "$$HOME" # $$ là ký tự $, Compose không thay thế

Trong đó:

  • ${LOG_LEVEL} (hay $LOG_LEVEL): giá trị của biến. Biến không có thì Compose cảnh báo và dùng chuỗi rỗng.
  • ${TAG:-mac-dinh}: dùng mac-dinh khi biến không có hoặc rỗng (${TAG-mac-dinh} chỉ khi không có).
  • ${APP_SECRET:?thông báo}: biến bắt buộc, không có hoặc rỗng thì Compose dừng. Hợp với secret: báo lỗi ngay còn hơn chạy với mật khẩu rỗng.
  • $$: ký tự $ thật, cho lệnh shell chạy trong container (phần 5).
docker compose config
# time="2026-11-24T14:13:07Z" level=warning msg="The \"LOG_LEVEL\" variable is not set. Defaulting to a blank string."
# error while interpolating services.app.environment.APP_SECRET: required variable APP_SECRET is missing a value: chưa đặt APP_SECRET

Giá trị lấy từ đâu.

Compose lấy giá trị từ biến môi trường của shell đang chạy lệnh và từ một file biến môi trường (dạng TÊN=GIÁ_TRỊ như --env-file của docker run ở bài 9). File tên đúng là .env nằm trong thư mục project được Compose tự đọc. Muốn dùng file khác thì chỉ định bằng --env-file (khi đó .env không được đọc) hoặc biến COMPOSE_ENV_FILES. Trong bài mình dùng tên taskflow.env và ghi rõ file đang dùng:

cat > taskflow.env <<'EOF'
# file thử: TÊN=GIÁ_TRỊ, dòng bắt đầu bằng # là comment
TAG=tu-file
LOG_LEVEL=debug
APP_SECRET=doi-mat-khau-nay
EOF
docker compose --env-file taskflow.env run --rm -q app
# APP_HOME=$HOME
# APP_LEVEL=debug
# APP_SECRET=doi-mat-khau-nay
# APP_TAG=tu-file
TAG= LOG_LEVEL=info docker compose --env-file taskflow.env run --rm -q app
# APP_HOME=$HOME
# APP_LEVEL=info
# APP_SECRET=doi-mat-khau-nay
# APP_TAG=mac-dinh

Lệnh thứ hai cho thấy biến của shell thắng file: LOG_LEVEL=info đè debug, TAG= (rỗng) cũng đè tu-file rồi :- cho ra mac-dinh. Các biến trong .env/--env-file chỉ phục vụ interpolation, không tự vào container: chỉ chỗ nào ghi ${...} mới nhận giá trị.

Lưu ý: docker compose config in cấu hình đã thay giá trị, tức in luôn secret:

docker compose --env-file taskflow.env config | grep APP_
# ...
#       APP_SECRET: doi-mat-khau-nay
# ...
docker compose --env-file taskflow.env config --no-interpolate | grep APP_
# ...
#       APP_SECRET: ${APP_SECRET:?chưa đặt APP_SECRET}
# ...

Một bước "in cấu hình cho dễ debug" trong CI (bài 24) sẽ ghi secret vào log build, nơi nhiều người đọc được và lưu lâu. Trong CI chỉ dùng config --quiet (kiểm tra hợp lệ, không in gì) hoặc --no-interpolate.

3. env_file và environment.

Key env_file của service nghe giống --env-file nhưng làm việc khác: nó đưa mọi biến trong file vào container, như docker run --env-file, và không dùng cho interpolation. Tạo envfile.yaml:

services:
  app:
    image: alpine:3.24
    command: ["sh", "-c", "env | grep -e ^APP_ -e ^TAG | sort"]
    env_file: app.env
    environment:
      APP_LEVEL: error
      APP_TAG: ${TAG:-mac-dinh}
cat > app.env <<'EOF'
APP_LEVEL=warn
APP_FROM_FILE=co
TAG=trong-app-env
EOF
docker compose -f envfile.yaml run --rm -q app
# APP_FROM_FILE=co
# APP_LEVEL=error
# APP_TAG=mac-dinh
# TAG=trong-app-env
docker compose -f envfile.yaml run --rm -q -e APP_LEVEL=trace app
# APP_FROM_FILE=co
# APP_LEVEL=trace
# ...

Mọi biến trong app.env đều vào container, kể cả TAG. Nhưng TAG=trong-app-env không ảnh hưởng tới ${TAG:-mac-dinh}, vì interpolation chỉ nhìn shell và .env/--env-file. Thứ tự ưu tiên trong container, nguồn sau thắng: ENV của image < env_file < environment < docker compose run -e (chi tiết trong tài liệu của Compose).

Ghi secret vào env_file thì secret thành biến môi trường, ai chạy được docker inspect cũng thấy (bài 15).

4. Secrets trong Docker Compose.

Secret của Compose là một file chỉ đọc ở /run/secrets/<tên> trong container. Key secrets cấp cao nhất khai báo nguồn: file (file trên máy) hoặc environment (một biến, lấy từ shell hoặc .env/--env-file như phần 2). Key secrets trong service cấp secret cho service đó, không ghi thì service không thấy. Thử cả hai nguồn với một user không phải root:

mkdir -p secrets
printf 'doi-mat-khau-nay' > secrets/db_password.txt
chmod 600 secrets/db_password.txt

- secret.yaml

services:
  app:
    image: alpine:3.24
    user: "65532" # như user nonroot của distroless
    command: ["sh", "-c", "ls -ln /run/secrets; cat /run/secrets/tu_env; echo; cat /run/secrets/token; echo; cat /run/secrets/tu_file"]
    secrets:
      - tu_file
      - tu_env
      - source: tu_env # cùng secret, gắn thêm ở tên khác với owner và quyền riêng
        target: token
        uid: "65532"
        mode: 0400

secrets:
  tu_file:
    file: ./secrets/db_password.txt
  tu_env:
    environment: APP_SECRET
docker compose -f secret.yaml --env-file taskflow.env run --rm -q app
# total 12
# -r--------    1 65532    0               16 Nov 24 14:13 token
# -r--r--r--    1 0        0               16 Nov 24 14:13 tu_env
# -rw-------    1 1000     1000            16 Nov 24 14:13 tu_file
# doi-mat-khau-nay
# doi-mat-khau-nay
# cat: can't open '/run/secrets/tu_file': Permission denied
docker compose -f secret.yaml --env-file taskflow.env create app
# ...
docker inspect -f '{{json .Mounts}}' thu19-app-1
# [{"Type":"bind","Source":"/tmp/thu19/secrets/db_password.txt","Destination":"/run/secrets/tu_file","Mode":"","RW":false,"Propagation":"rprivate"}]
docker compose -f secret.yaml down
# ...

Dạng ngắn (- tu_file) gắn ở /run/secrets/tu_file, dạng dài có thêm target, uid, gid, mode. Hai nguồn được đưa vào theo hai cách:

  • Nguồn file: bind mount file của máy (bài 13), giữ nguyên owner và quyền của máy (1000, 600), uid/gid/mode không áp dụng được. User 65532 bị Permission denied: với image nonroot, file cần quyền 644 hoặc đúng uid của user trong container.
  • Nguồn environment: Compose chép giá trị vào container lúc tạo, mặc định owner root, quyền 0444, và áp dụng uid/mode: token chỉ user 65532 đọc được.

Image chạy bằng root rồi mới đổi user như postgres thì đọc secret lúc còn là root, quyền 600 vẫn chạy (mình đã thử). inspect chỉ thấy đường dẫn của nguồn file, không thấy giá trị nào. Tất nhiên ai gọi được Docker daemon vẫn docker exec ... cat được secret: secret chỉ giúp giá trị không nằm ở những chỗ hay bị in ra như inspect, log hay config.

5. Đưa mật khẩu của TaskFlow ra khỏi compose.yaml.

Mỗi secret của TaskFlow sẽ chỉ có một nguồn: một biến trong taskflow.env. Service đọc được file nhận nó dạng secret (nguồn environment), service chỉ đọc biến môi trường nhận qua interpolation. Phần thay đổi của examples/19-secrets/compose.yaml so với bài 17 (bản đầy đủ trong repo của series):

# TaskFlow (bài 17) không còn mật khẩu trong file: giá trị lấy từ biến môi trường
# (taskflow.env hoặc .env, không commit), vào container qua secrets hoặc environment.
# Chạy: docker compose --env-file taskflow.env up -d --wait
name: taskflow

services:
  db:
    # ...
    environment:
      POSTGRES_USER: taskflow
      POSTGRES_DB: taskflow
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password # image đọc mật khẩu từ file (bài 15)
    secrets:
      - db_password
    # ...

  redis:
    image: redis:8-alpine
    restart: unless-stopped
    # $$ để Compose không thay thế: shell trong container đọc file secret rồi chạy entrypoint gốc của image
    command: ["sh", "-c", "exec docker-entrypoint.sh redis-server --appendonly yes --requirepass \"$$(cat /run/secrets/redis_password)\""]
    secrets:
      - redis_password
    volumes:
      - redisdata:/data
    healthcheck:
      test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/redis_password)\" redis-cli ping | grep -q PONG"]
      # ...

  migrate: # chạy migration rồi thoát, mỗi lần up
    # ...
    environment:
      DATABASE_URL: postgres://taskflow:${DB_PASSWORD:?thiếu DB_PASSWORD, xem taskflow.env.example}@db:5432/taskflow?sslmode=disable
    # ...

  api:
    # ...
    environment: # TaskFlow chỉ đọc biến môi trường, không đọc file secret
      TASKFLOW_JWT_SECRET: ${TASKFLOW_JWT_SECRET:?thiếu TASKFLOW_JWT_SECRET, xem taskflow.env.example}
      DATABASE_URL: postgres://taskflow:${DB_PASSWORD:?thiếu DB_PASSWORD, xem taskflow.env.example}@db:5432/taskflow?sslmode=disable
      TASKFLOW_REDIS_URL: redis://:${REDIS_PASSWORD:?thiếu REDIS_PASSWORD, xem taskflow.env.example}@redis:6379/0
    # ...

secrets: # Compose chép giá trị của biến vào /run/secrets/<tên> trong container
  db_password:
    environment: DB_PASSWORD
  redis_password:
    environment: REDIS_PASSWORD

volumes:
  # ...

Trong đó:

  • db: POSTGRES_PASSWORD_FILE thay POSTGRES_PASSWORD, entrypoint của image đọc mật khẩu từ file khi khởi tạo database.
  • redis: Redis không có biến _FILE. sh -c đọc file bằng $(cat ...) rồi exec sang docker-entrypoint.sh của image, để entrypoint vẫn đổi sang user redis như khi chạy thẳng redis-server. Viết $$ vì đây là cú pháp của shell trong container, không phải của Compose. Healthcheck đặt REDISCLI_AUTH theo cùng cách.
  • Hai secret dùng nguồn environment, cùng biến với interpolation. Dùng nguồn file thì mật khẩu PostgreSQL phải nằm ở cả file secret lẫn DATABASE_URL, lại hai chỗ.

Service psql trong compose.override.yaml bỏ PGPASSWORD, dùng chung secret db_password (Compose gộp hai file như bài 18):

  psql: # công cụ, chỉ chạy khi bật profile tools
    # ...
    # đọc mật khẩu từ secret rồi chạy psql, tham số sau "run --rm psql" được nối vào psql
    entrypoint: ["sh", "-c", "PGPASSWORD=\"$$(cat /run/secrets/db_password)\" exec psql \"$$@\"", "psql"]
    environment:
      PGHOST: db
      PGUSER: taskflow
      PGDATABASE: taskflow
    secrets:
      - db_password # khai báo ở compose.yaml
    # ...

Thêm hai file được commit:

- examples/19-secrets/taskflow.env.example

# Chép thành taskflow.env (hoặc .env) rồi đổi giá trị. Không commit file đã chép.
# Tạo giá trị ngẫu nhiên: openssl rand -hex 32 (chỉ có chữ số hex, an toàn khi nằm trong URL)
DB_PASSWORD=doi-mat-khau-nay
REDIS_PASSWORD=doi-mat-khau-nay
TASKFLOW_JWT_SECRET=doi-mat-khau-nay-doi-mat-khau-nay

- examples/19-secrets/.gitignore

# file chứa giá trị thật, không commit
.env
taskflow.env

Mật khẩu có @, :, / sẽ làm hỏng DATABASE_URL, chuỗi hex của openssl rand -hex 32 thì không. Chạy thử:

cd ~/taskflow-docker/examples/19-secrets
grep -c doi-mat-khau-nay compose.yaml compose.override.yaml
# compose.yaml:0
# compose.override.yaml:0
docker compose config --quiet
# error while interpolating services.api.environment.DATABASE_URL: required variable DB_PASSWORD is missing a value: thiếu DB_PASSWORD, xem taskflow.env.example
# ...
cp taskflow.env.example taskflow.env
export COMPOSE_ENV_FILES=taskflow.env
time docker compose up -d --wait
# ...
#  Container taskflow-api-1 Healthy
# real	0m 14.37s
docker compose exec db ls -ln /run/secrets
# total 4
# -r--r--r--    1 0        0               16 Nov 24 14:13 db_password
docker top taskflow-redis-1
# PID                 USER                TIME                COMMAND
# 15199               999                 0:00                redis-server *:6379
docker compose exec redis redis-cli ping
# NOAUTH Authentication required.
docker inspect taskflow-db-1 taskflow-redis-1 | grep -c doi-mat-khau-nay
# 0
docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' taskflow-api-1 | grep -e URL -e SECRET
# DATABASE_URL=postgres://taskflow:doi-mat-khau-nay@db:5432/taskflow?sslmode=disable
# TASKFLOW_JWT_SECRET=doi-mat-khau-nay-doi-mat-khau-nay
# TASKFLOW_REDIS_URL=redis://:doi-mat-khau-nay@redis:6379/0
docker compose run --rm psql -c 'select count(*) from users'
# ...
#      0
# (1 row)

export COMPOSE_ENV_FILES=taskflow.env thay cho gõ --env-file taskflow.env ở mọi lệnh sau trong terminal này, đặt tên file là .env thì không cần cả hai. Redis chạy bằng user 999 (redis) và vẫn đòi mật khẩu. docker top không lộ mật khẩu vì Redis tự đổi tên process, còn Config.Cmd chỉ chứa chữ $(cat ...). db và redis không còn mật khẩu trong inspect, riêng api thì còn.

TaskFlow chỉ đọc biến môi trường.

Hàm loadConfig của TaskFlow (bài 28 series Go) chỉ đọc biến môi trường và flag, không có kiểu DATABASE_URL_FILE. Các lựa chọn:

  • Script entrypoint đọc /run/secrets/*, export rồi chạy /api: image distroless static (bài 10) không có shell. Build image riêng có thêm shell thì mất đúng ưu điểm đó và phải bảo trì thêm một image.
  • Thêm hỗ trợ _FILE vào TaskFlow (vài dòng Go): sạch nhất về lâu dài, nhưng là việc của series Go.
  • Truyền bằng biến môi trường lấy từ taskflow.env không commit.

Mình chọn cách cuối vì nó giải quyết đúng hai vấn đề ở phần 1: không còn secret trong git, và mỗi secret chỉ sửa ở một chỗ. Cái giá là ai chạy được docker inspect thấy ba giá trị của api, nhưng người đó vốn cũng docker exec đọc được secret dạng file. TaskFlow không in chúng ra log: dòng đã đọc cấu hình ghi config.database_url="[đã ẩn]".

6. Đổi secret.

Secret bị lộ hoặc tới kỳ thay thì phải đổi. Thử với Redis trước:

sed -i 's/^REDIS_PASSWORD=.*/REDIS_PASSWORD=mat-khau-redis-moi/' taskflow.env
docker compose up -d --wait
#  Container taskflow-db-1 Running
#  Container taskflow-redis-1 Running
#  Container taskflow-api-1 Recreate
# ...
curl -s localhost:8080/ready
# ok
docker compose logs api | grep 'chưa kết nối được Redis'
# api-1  | time=2026-11-24T14:13:27.669Z level=WARN msg="chưa kết nối được Redis" err="WRONGPASS invalid username-password pair or user is disabled."

Compose tạo lại api vì TASKFLOW_REDIS_URL đổi, nhưng để nguyên redis: nó so cấu hình của service, không so giá trị bên trong secret. Redis giữ mật khẩu cũ, api bị WRONGPASS, còn /ready vẫn ok vì chỉ kiểm tra database (bài 17), không có gì báo lỗi. Phải tạo lại service giữ secret:

docker compose up -d --wait --force-recreate redis
#  Container taskflow-redis-1 Recreate
# ...
#  Container taskflow-redis-1 Healthy
docker compose exec redis sh -c 'REDISCLI_AUTH="$(cat /run/secrets/redis_password)" redis-cli info clients' | grep connected_clients
# connected_clients:5

Client Redis của api tự kết nối lại bằng mật khẩu mới. Với PostgreSQL thì khác: POSTGRES_PASSWORD_FILE chỉ được đọc khi khởi tạo database rỗng (bài 15). Chỉ sửa taskflow.env rồi up thì migrate thoát với password authentication failed for user "taskflow". Phải đổi trong database trước, lúc file vẫn còn mật khẩu cũ (service psql đăng nhập bằng nó):

docker compose run --rm psql -c "ALTER ROLE taskflow PASSWORD 'mat-khau-db-moi'"
# ...
# ALTER ROLE
sed -i 's/^DB_PASSWORD=.*/DB_PASSWORD=mat-khau-db-moi/' taskflow.env
docker compose up -d --wait
# ...
#  Container taskflow-migrate-1 Recreate
#  Container taskflow-api-1 Recreate
# ...
docker compose ps -a --format 'table {{.Name}}\t{{.Status}}'
# NAME                 STATUS
# taskflow-api-1       Up 5 seconds (healthy)
# taskflow-db-1        Up 31 seconds (healthy)
# taskflow-migrate-1   Exited (0) 5 seconds ago
# taskflow-redis-1     Up 12 seconds (healthy)

Làm thật thì đừng ghi mật khẩu trong -c (nó vào lịch sử shell): mở docker compose run --rm psql rồi gõ \password taskflow. Đổi TASKFLOW_JWT_SECRET chỉ cần sửa file và up -d, nhưng mọi access token đã ký bằng secret cũ (bài 33 series Go) mất hiệu lực ngay, người dùng phải đăng nhập lại. Token chỉ sống 15 phút nên thường chấp nhận được.

Dọn dẹp.

Xóa stack, volume, image taskflow-api:dev do file override build, biến COMPOSE_ENV_FILES và thư mục thử. File taskflow.env giữ lại (git đã bỏ qua nó):

docker compose down -v
# ...
#  Network taskflow_default Removed
docker rmi taskflow-api:dev
# Untagged: taskflow-api:dev
# ...
unset COMPOSE_ENV_FILES
rm -r /tmp/thu19
docker volume ls
# DRIVER    VOLUME NAME

7. Lời kết.

Như vậy qua bài này các bạn đã nắm biến môi trường và secret trong Docker Compose: interpolation với ${VAR}, :-, :?, $$, giá trị lấy từ shell, .env hoặc --env-file, env_file khác interpolation ra sao, config làm lộ secret, secrets: với nguồn file và environment cùng chuyện quyền file, và đổi secret mà không làm hỏng stack. File Compose của TaskFlow giờ commit được mà không lộ gì. Bài sau mình sẽ chuẩn bị cho production: log driver và xoay vòng log, giới hạn CPU, memory và stop_grace_period.

Đăng ký nhận tin.

Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha