我们这里采用多阶段构建,先用nodejs构建vue项目,然后将静态文件交给nginx托管

# Stage 1: Build the Vue application
# 选择一个 Node.js 镜像 (版本需与 ruoyi-ui 兼容, 查看 package.json 或咨询项目)
FROM node:18 AS builder

WORKDIR /app

# 复制package.json到工作目录
COPY package*.json ./

# 配置淘宝镜像加速器
RUN npm config set registry https://registry.npmmirror.com
# 执行安装
RUN npm install husky --save-dev && npm install
# 复制源代码
copy . . 
# 进行build构建
RUN npm run build:stage

# Stage 2: Serve the built files using Nginx
FROM nginx:1.22-alpine # 使用轻量级Nginx镜像
# 移除默认的nginx配置
RUN rm /etc/nginx/conf.d/default.conf
# 复制自定义的nginx配置
COPY ./nginx.conf /etc/nginx/conf.d/default.conf

RUN rm -rf /usr/share/nginx/html/*
# 将上一阶段的构建文件放到nginx的web根目录
COPY --from=builder /app/dist /usr/share/nginx/html

# 暴露 80
EXPOSE 80

# 启动 nginx
CMD ["nginx", "-g", "daemon off;"]

创建自定义的nginx.conf文件

# nginx.conf

server {
    listen       80;
    server_name  localhost; # 或者你的域名

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    error_log /var/log/nginx/error.log warn;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        # 解决 Vue Router History 模式下刷新 404 的问题
        try_files $uri $uri/ /index.html;
    }

    # 配置 API 代理,将前端的 /prod-api 请求转发给后端服务
    # /prod-api 这个前缀需要与 ruoyi-ui/.env.production 中的 VUE_APP_BASE_API 一致
    location /prod-api/ {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # 转发到后端服务的地址和端口 (ruoyi-backend 是 docker-compose 中的服务名)
        proxy_pass http://ruoyi-backend:8080/;

        # 可选: 移除 /prod-api 前缀转发给后端
        # rewrite ^/prod-api/(.*)$ /$1 break;
        # RuoYi 后端通常不需要移除前缀,可以直接接收 /prod-api/ 开头的请求
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}