55 lines
1.4 KiB
Docker
55 lines
1.4 KiB
Docker
# 构建阶段
|
|
FROM node:18-alpine AS build-stage
|
|
|
|
# 设置工作目录
|
|
WORKDIR /app
|
|
|
|
# 复制依赖配置文件
|
|
COPY package*.json ./
|
|
|
|
# 安装依赖 (包含开发依赖,构建需要)
|
|
RUN npm ci --include=dev --no-audit --no-fund
|
|
|
|
# 复制源代码
|
|
COPY . .
|
|
|
|
# 创建 .dockerignore 忽略的文件夹
|
|
RUN mkdir -p dist
|
|
|
|
# 构建应用
|
|
RUN npm run build
|
|
|
|
# 生产阶段 - 使用更轻量的 nginx 镜像
|
|
FROM nginx:1.25-alpine AS production-stage
|
|
|
|
# 创建非 root 用户
|
|
RUN addgroup -g 1001 -S nginx-user && \
|
|
adduser -S -D -H -u 1001 -h /var/cache/nginx -s /sbin/nologin -G nginx-user -g nginx-user nginx-user
|
|
|
|
# 复制自定义 Nginx 配置
|
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
|
|
|
# 复制构建产物到 Nginx
|
|
COPY --from=build-stage --chown=nginx-user:nginx-user /app/dist /usr/share/nginx/html
|
|
|
|
# 设置正确的权限
|
|
RUN chown -R nginx-user:nginx-user /usr/share/nginx/html && \
|
|
chown -R nginx-user:nginx-user /var/cache/nginx && \
|
|
chown -R nginx-user:nginx-user /var/log/nginx && \
|
|
chown -R nginx-user:nginx-user /etc/nginx/conf.d && \
|
|
touch /var/run/nginx.pid && \
|
|
chown -R nginx-user:nginx-user /var/run/nginx.pid
|
|
|
|
# 切换到非 root 用户
|
|
USER nginx-user
|
|
|
|
# 暴露端口
|
|
EXPOSE 8080
|
|
|
|
# 健康检查
|
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
|
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/ || exit 1
|
|
|
|
# 启动 Nginx
|
|
CMD ["nginx", "-g", "daemon off;"]
|