1. 前言
項目運行過程圖:
對于前端項目通過命令 npm run build 打包后,無法直接運行。存在如下錯誤:
可以通過配置 nginx 服務器運行前端項目解決如上問題。
2. Nginx 運行
采用 docker 鏡像的方式運行,docker-compose.yml 文件內容如下:
version: '3'
services:nginx:image: nginxcontainer_name: my-nginxextra_hosts:- "host.docker.internal:host-gateway"ports:- "8081:80"volumes:- ./nginx/conf.d:/etc/nginx/conf.d- ./nginx/html:/usr/share/nginx/html- ./nginx/logs:/var/log/nginx
此時,nginx 目錄下會創建一個新的 nginx 文件夾。
conf.d 文件夾 → nginx 配置文件
html → 前端打包文件
logs → nginx 日志文件
配置文件說明:
extra_hosts 用于在容器內部添加額外的主機名解析記錄。配置 host.docker.internal:host-gateway 允許容器通過 host.docker.internal 訪問宿主機的服務。
3. Nginx 配置文件
命名必須為***.conf
,例如 ruoyi.conf
server {listen 80;server_name localhost;charset utf-8;# 明確指定根目錄,確保路徑正確root /usr/share/nginx/html;index index.html index.htm;location / {# root html;try_files $uri /index.html;# index index.html index.htm;}# 命名location用于安全地處理SPA回退location @spa-fallback {rewrite ^ /index.html break; # 使用break防止進一步重寫}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;proxy_pass http://host.docker.internal:8080/;}location /dev-api/ { # 將 prod-api 改為 dev-apiproxy_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;proxy_pass http://host.docker.internal:8080/; # 注意這里的斜杠,它會影響URI傳遞}# springdoc proxylocation ~ ^/v3/api-docs/(.*) {proxy_pass http://host.docker.internal:8080/v3/api-docs/$1;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
此時在宿主機可以通過http://localhost:8081
訪問。