Docker构建前端应用的多阶段构建优化
请编写一个优化的Dockerfile,使用多阶段构建(multi-stage build)来减小前端应用镜像体积,并启用nginx gzip/brotli压缩。
回答
我还是少年
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm install -g pnpm && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
FROM nginx:stable-alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
events { worker_connections 1024; }
http {
gzip on; gzip_types text/css application/javascript;
brotli on; brotli_types text/css application/javascript;
server {
listen 80;
root /usr/share/nginx/html;
location / { try_files $uri $uri/ /index.html; }
location ~*\.(js|css|png)$ { expires 1y; add_header Cache-Control "public, immutable"; }
}
}
优化:最终镜像仅含nginx+静态文件(~20MB),利用Docker层缓存加速CI。