# 优化版多阶段构建Dockerfile # 这个版本针对生产环境进行了优化,镜像更小,安全性更高 # ================================ # 阶段1: 前端构建 # ================================ FROM node:18-alpine as frontend-builder # 设置工作目录 WORKDIR /app # 只复制package文件,利用Docker缓存 COPY client/package*.json ./ # 安装依赖 RUN npm ci --only=production && \ npm cache clean --force # 复制源代码 COPY client/ ./ # 构建前端 RUN npm run build # ================================ # 阶段2: 后端构建 # ================================ FROM node:18-alpine as backend-builder WORKDIR /app # 复制package文件 COPY server/package*.json ./ # 安装依赖 RUN npm ci --only=production && \ npm cache clean --force # 复制源代码 COPY server/ ./ # ================================ # 阶段3: 最终生产镜像 # ================================ FROM node:18-alpine # 安装运行时依赖 RUN apk add --no-cache \ nginx \ supervisor \ wget \ curl \ dumb-init \ && rm -rf /var/cache/apk/* # 创建应用用户 RUN addgroup -g 1001 -S appuser && \ adduser -S appuser -u 1001 -G appuser # 创建必要的目录 RUN mkdir -p /app /var/log/nginx /var/log/supervisor /run/nginx && \ chown -R appuser:appuser /app /var/log/nginx /var/log/supervisor /run/nginx # 设置工作目录 WORKDIR /app # 复制后端文件 COPY --from=backend-builder --chown=appuser:appuser /app ./ # 复制前端构建文件 COPY --from=frontend-builder --chown=appuser:appuser /app/dist ./public # 创建nginx配置 COPY --chown=appuser:appuser <