# 构建阶段 FROM node:18-alpine as build # 安装构建依赖 RUN apk add --no-cache git WORKDIR /app # 创建非root用户 RUN addgroup -g 1001 -S nodejs && \ adduser -S nodejs -u 1001 # 复制package.json和package-lock.json COPY --chown=nodejs:nodejs package*.json ./ # 切换到nodejs用户 USER nodejs # 安装依赖 RUN npm ci && npm cache clean --force # 复制源代码 COPY --chown=nodejs:nodejs . . # 构建应用 RUN npm run build # 生产阶段 FROM nginx:alpine # 安装wget用于健康检查 RUN apk add --no-cache wget # 创建nginx用户目录 RUN mkdir -p /var/cache/nginx && \ chown -R nginx:nginx /var/cache/nginx && \ chown -R nginx:nginx /var/log/nginx && \ chown -R nginx:nginx /etc/nginx/conf.d # 复制构建的文件到nginx COPY --from=build --chown=nginx:nginx /app/dist /usr/share/nginx/html # 复制nginx配置 COPY --chown=nginx:nginx nginx.conf /etc/nginx/conf.d/default.conf # 切换到nginx用户 USER nginx # 暴露端口 EXPOSE 80 # 健康检查 HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost:80 || exit 1 # 启动nginx CMD ["nginx", "-g", "daemon off;"]