Skip to content

管理后台部署

本文档说明如何将 todo_admin(Vue 3 + Vite 管理控制台 SPA)打包为 Docker 镜像并部署运行。

镜像基于 todo_admin/Dockerfile(多阶段构建:Node 20 编译 → Nginx 1.27 提供静态文件 + /api 反向代理),最终镜像默认监听 容器 80 端口,对外通过 -p 映射。


1. 镜像构成

阶段基础镜像作用
构建node:20-slimnpm ci + npm run build 生成 dist/
运行nginx:1.27-alpine托管静态资源,并把 /api/ 反代到后端

关键文件:

  • Dockerfile — 多阶段构建
  • nginx.conf.template — Nginx 模板,/api/ 反代地址用 ${API_PROXY_PASS} 占位
  • docker-entrypoint.sh — 容器启动时用 envsubst 注入 Nginx 配置

2. 构建镜像

方式 A:本地构建

bash
cd todo_admin
docker build -t itodo-admin:latest .

方式 B:通过 CNB Cloud Native Build 自动构建

仓库根目录 .cnb.yml 已配置在 main 分支 push 时自动构建并推送三个镜像:

  • docker.cnb.cool/<组织>/<项目>/api:latest
  • docker.cnb.cool/<组织>/<项目>/web:latest
  • docker.cnb.cool/<组织>/<项目>/admin:latest

只需 git pushmain,CNB 会自动完成构建与推送。


3. 环境变量

变量必填默认值说明
API_PROXY_PASShttp://todo_api:80/api/ 反代的后端地址(不含 /api 前缀)

4. 部署方式

方式一:docker run

bash
docker run -d --name itodo-admin \
  -p 8081:80 \
  -e API_PROXY_PASS=http://192.168.1.100:3000 \
  itodo-admin:latest

访问 http://localhost:8081 使用管理后台。

方式二:docker-compose(完整部署)

yaml
services:
  db:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: your_db_password
      POSTGRES_DB: todo_api_production
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 10

  api:
    image: itodo-api:latest
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
    expose:
      - "80"
    environment:
      RAILS_MASTER_KEY: your_master_key
      DB_HOST: db
      DB_PORT: 5432
      DB_USERNAME: postgres
      DB_PASSWORD: your_db_password
      DB_NAME: todo_api_production

  web:
    image: itodo-web:latest
    restart: unless-stopped
    depends_on:
      - api
    ports:
      - "8080:80"
    environment:
      API_PROXY_PASS: http://api:80

  admin:
    image: itodo-admin:latest
    restart: unless-stopped
    depends_on:
      - api
    ports:
      - "8081:80"
    environment:
      API_PROXY_PASS: http://api:80

volumes:
  pgdata:

启动:

bash
docker compose up -d

访问:

  • Web 端:http://localhost:8080
  • 管理后台:http://localhost:8081

5. 验证

bash
# 管理后台首页
curl -I http://localhost:8081/

# 反代后端健康检查(经 Nginx 转发)
curl http://localhost:8081/api/health

浏览器打开 http://localhost:8081,使用管理员账号登录。


6. 初始化管理员

首次部署后,需要手动设置一个管理员用户:

bash
docker compose exec api bin/rails runner "
  user = User.find_or_initialize_by(email: 'admin@itodo.com')
  user.password = 'Zero473316'
  user.password_confirmation = 'Zero473316'
  user.display_name = 'Admin'
  user.role = 'admin'
  user.save!
  puts 'Admin user ready'
"

管理员角色只能通过数据库直接设置,管理后台不支持修改用户角色。


7. 常见问题

现象原因 / 解决
登录提示"需要管理员权限"账号 role 不是 admin,需要通过数据库设置
页面能打开但 API 请求 404检查 API_PROXY_PASS 是否指向正确的后端地址
刷新子路由 404Nginx 已配置 try_files $uri /index.html(SPA 回退)
镜像推送 403确认 CNB 仓库存在且 CI 凭证有写权限

基于 VitePress 构建