Skip to content

React 部署

本文适用于使用 Vite 构建的 React 单页应用。生产镜像分为两个阶段:Node.js 负责生成 dist/,Nginx 负责提供静态文件。

Dockerfile

在项目根目录创建 Dockerfile

dockerfile
FROM node:24-alpine AS builder

WORKDIR /app

RUN corepack enable

COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile

COPY . .

ARG VITE_API_BASE_URL
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL

RUN pnpm build

FROM nginx:alpine AS runner

COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

VITE_API_BASE_URL 是构建参数,仅用于演示客户端环境变量。未使用时可删除对应的 ARGENV

Nginx 配置

在项目根目录创建 nginx.conf

nginx
server {
    listen 80;
    server_name _;

    root /usr/share/nginx/html;
    index index.html;

    location /assets/ {
        try_files $uri =404;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    location / {
        try_files $uri $uri/ /index.html;
    }
}

try_files 将不存在的路径回退到 index.html,用于支持 React Router 等客户端路由。多页面应用或没有客户端路由时,应按实际路由结构调整。

.dockerignore

bash
node_modules
dist
.git
.env*
*.log

.env* 中的值不会自动进入构建过程。需要暴露给客户端的 Vite 变量应通过构建参数传入,且不得包含密钥。

Docker Compose

将项目代码放入部署目录并进入:

bash
mkdir -p ~/apps/react-app
cd ~/apps/react-app

创建 compose.yml

yaml
services:
  app:
    build:
      context: .
      args:
        VITE_API_BASE_URL: https://api.example.com
    image: react-app
    container_name: react-app
    restart: unless-stopped
    ports:
      - '8080:80'

启动服务:

bash
docker compose up -d

访问 http://<服务器地址>:8080 验证应用。更新客户端环境变量后重新构建并启动服务:

bash
docker compose up -d --build

参考

基于 MIT 许可发布