一、问题描述:
docker下的nginx部署前端项目报500、404错误。
二、先说解决办法:
1. docker下的nginx只能读到挂载路径下面的文件,需要将编译好的前端项目文件夹复制到nginx挂载的路径下;
2. docker下的nginx的nginx.conf配置文件中的localhost地址无法访问,需要配置成服务器IP地址。
三、再说问题分析:
先看看nginx安装和挂载情况:docker下安装nginx教程。
根据若依文档中的nginx配置修改了挂载出来的nginx.conf配置文件结果报500错误,百度搜了很多解决方法都没有解决,通过查看nginx错误日志看到报错:
*1 rewrite or internal redirection cycle while internally redirecting to "//index.html/index.html/index.html/index.html/index.html/index.html/index.html/index.html/index.html/index.html/index.html", client: 192.168.118.1, server: 192.168.118.128, request: "GET / HTTP/1.1", host: "192.168.118.128"
搜索该错误找到官方回复:
修改配置文件后没有解决,随后删掉
try_files $uri $uri/ /index.html;
这行代码后再次访问报404错误。通过查看nginx错误日志看到报错:
"/mydata/nginx/html/dist/index.html" is not found (2: No such file or directory), client: 192.168.118.1, server: 192.168.118.128, request: "GET / HTTP/1.1", host: "192.168.118.128"
结合百度搜索该问题才知道是docker下的nginx只能读到挂载路径下面的文件(菜鸡表现,学无止境啊),所以将编译好的前端项目文件夹复制到nginx挂载的路径下,并且修改配置文件中的root路径,再次访问成功加载首页。
但是提示后台接口错误。同样的思路想到nginx.conf配置文件中的localhost地址无法访问,改成服务器IP项目正常运行。
贴出nginx.conf配置信息
user root;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root /usr/share/nginx/html/dist; #根目录路径需要在nginx挂载路径下
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
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://192.168.118.128:88/; #访问地址必须问服务器IP不能用localhost
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}