# 测试/正式环境部署编排（正式口令不得写入本文件）。
# 使用：复制 .env.example 为 .env 填写；TAG 指定镜像标签（默认取当前提交 sha）。
# 例：TAG=v1.0.0-rc1 docker compose -f compose.yaml up -d --build
#
# 同宿主机多套环境（测试 + 正式）必须各自设置：
#   COMPOSE_PROJECT_NAME / APP_CONTAINER_NAME / APP_PORT_MAP 互不相同。
# 正式环境启用 HTTPS 反代：.env 中设 COMPOSE_PROFILES=tls（先跑 tls/gen-cert.sh）。

name: ${COMPOSE_PROJECT_NAME:-deploy}

services:
  app:
    container_name: ${APP_CONTAINER_NAME:-caiwuzongzhang-app}
    image: caiwuzongzhang:${TAG:-latest}
    build:
      context: ..
      dockerfile: deploy/Dockerfile
    env_file:
      - .env
    # 绑定挂载 data/ 时，容器运行 uid 必须与数据目录属主一致（.env 里设
    # APP_UID/APP_GID，正式与测试环境各自填写，默认镜像内 app=10001）
    user: "${APP_UID:-10001}:${APP_GID:-10001}"
    ports:
      - "${APP_PORT_MAP:-4173:4173}"
    volumes:
      - ../data:/app/data
    init: true
    restart: unless-stopped
    read_only: true
    tmpfs:
      - /tmp:size=64m,mode=1777
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    pids_limit: 128
    mem_limit: 512m
    cpus: 1.0
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4173/', timeout=2)"]
      interval: 15s
      timeout: 3s
      retries: 5
      start_period: 10s

  # 可选 HTTPS 反向代理（正式环境用）：COMPOSE_PROFILES=tls 启用。
  # 证书由 tls/gen-cert.sh 生成的内部 CA 签发（内网自受管信任），公司电脑
  # 安装 tls/certs/ca.crt 一次即可无告警访问。
  proxy:
    container_name: ${PROXY_CONTAINER_NAME:-caiwuzongzhang-proxy}
    image: nginx:1.27-alpine
    profiles: ["tls"]
    ports:
      - "${PROXY_PORT_MAP:-8443:8443}"
    volumes:
      - ./tls/nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - ./tls/certs/server.crt:/etc/nginx/tls/server.crt:ro
      - ./tls/certs/server.key:/etc/nginx/tls/server.key:ro
    # 与证书文件属主一致的 uid/gid（默认 101=镜像 nginx 用户；宿主机生成证书时
    # 设为属主 uid/gid，保持 server.key 0600 不放宽）
    user: "${PROXY_UID:-101}:${PROXY_GID:-101}"
    depends_on:
      - app
    restart: unless-stopped
    read_only: true
    tmpfs:
      - /var/cache/nginx:size=16m,uid=${PROXY_UID:-101},gid=${PROXY_GID:-101},mode=700
      - /var/run:size=1m,uid=${PROXY_UID:-101},gid=${PROXY_GID:-101},mode=700
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    pids_limit: 64
    mem_limit: 64m
    cpus: 0.5
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"
    healthcheck:
      test: ["CMD", "wget", "-q", "--no-check-certificate", "-O", "/dev/null", "https://127.0.0.1:8443/"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s
