You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Docker Compose+Nginx部署Vue项目刷新页面出现404问题求助

解决Vue路由刷新404问题(Docker Compose + Nginx反向代理)

问题核心错误

你的配置存在两个关键问题,导致路由刷新时触发404:

  1. 前端Nginx根路径不匹配
    Dockerfile中已将Vue构建产物dist复制到容器的/usr/share/nginx/html,但前端服务的nginx.conf里却设置root /app;,Nginx找不到静态文件和index.html,直接返回404。

  2. 前端服务未挂载自定义Nginx配置
    Docker Compose的dc-front-end服务缺少volumes配置,导致前端容器使用Nginx默认配置,而非你写的包含try_files规则的自定义配置。

修复步骤

1. 修正前端Nginx的root路径

修改前端服务的nginx.conf,将根路径改为Dockerfile中指定的目录:

server {
    listen       80;
    server_name  localhost;
    # 匹配Dockerfile中dist的存放路径
    root   /usr/share/nginx/html;

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

    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

2. 配置前端服务挂载自定义Nginx配置

更新Docker Compose的dc-front-end服务,添加volumes挂载你的本地nginx.conf到容器内:

dc-front-end:
    # 保留你原有build/image等配置
    container_name: dc-front-end
    volumes:
      # 替换为你本地前端nginx.conf的实际路径
      - ./frontend/nginx.conf:/etc/nginx/nginx.conf
    ports:
      - 8080:80

3. 反向代理配置优化(可选)

为确保前端能正确识别请求来源,可在反向代理的location /中添加主机头配置:

location / {
    proxy_pass          http://dc-front-end:80;
    proxy_set_header    X-Forwarded-For $remote_addr;
    proxy_set_header    Host $host;
}

验证修复

执行以下命令重新部署服务:

docker-compose down
docker-compose up --build

此时访问任意Vue路由后刷新页面,404问题应已解决。

内容的提问来源于stack exchange,提问作者raklos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:45:30