Docker容器中Vue3+Nginx项目构建后静态资源加载失败问题
问题
在Docker容器中结合Nginx构建Vue3项目时遇到静态资源加载失败的问题,访问localhost:8080时控制台报错:
Uncaught SyntaxError: Unexpected token '<'
manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.
不使用Nginx直接构建项目一切正常,相关配置如下:
Dockerfile内容
# Non-prod as builder FROM node:18.13.0 as build-stage WORKDIR /app COPY package*.json ./ COPY package-lock.json ./ RUN npm ci COPY . . # Build the project RUN npm run build # Prod FROM nginx:1.19 as production-stage RUN mkdir /app COPY --from=build-stage /app/dist /app COPY ./.nginx/nginx.conf /etc/nginx/nginx.conf EXPOSE 80
nginx.conf内容
user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root /app; 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; } } }
容器启动命令
docker run -it -p 8080:80 --rm --name vue-app-1 user/vue-app
问题原因与解决办法
核心原因
这个报错的本质是Nginx返回给浏览器的静态资源(比如js、manifest.json)实际是index.html的内容,根本没找到对应的真实文件。问题出在Vue项目构建后的资源路径和Nginx配置不匹配:
- 当前Dockerfile是把Vue构建好的
dist目录内所有文件直接复制到容器的/app目录下,index.html和assets/、manifest.json等静态资源平级放在/app里。 - 如果Vue项目的资源基础路径(Vite中的
base,Vue CLI中的publicPath)不是根路径/,或者构建时生成的资源引用是相对路径,Nginx用root /app解析请求时会找不到对应资源,触发try_files规则返回index.html,浏览器把HTML当成JS/JSON解析自然报错。
解决步骤
方案1:修正Vue项目的资源路径配置
- 若使用Vite构建,打开
vite.config.js,将base设为'/':export default defineConfig({ base: '/', // 其他配置... }) - 若使用Vue CLI构建,打开
vue.config.js,将publicPath设为'/':module.exports = { publicPath: '/', // 其他配置... }
修改后重新构建镜像,确保静态资源的引用路径为根路径开头的绝对路径。
方案2:调整Docker复制路径和Nginx配置
无需修改Vue项目,直接调整Dockerfile和Nginx配置:
- 修改Dockerfile生产阶段的复制命令,将整个
dist目录复制到容器/app下:COPY --from=build-stage /app/dist /app/dist - 对应修改nginx.conf中的
root路径,指向/app/dist:location / { root /app/dist; index index.html; try_files $uri $uri/ /index.html; }
这样Nginx的根目录就是Vue构建后的dist文件夹,资源请求可正确匹配到文件。
验证方法
容器启动后,执行以下命令检查容器内文件结构,确认资源位置是否正确:
docker exec -it vue-app-1 ls -l /app
也可查看Nginx错误日志排查具体路径问题:
docker exec -it vue-app-1 cat /var/log/nginx/error.log
内容的提问来源于stack exchange,提问作者existentia
相关产品推荐
相关产品推荐

