nginx 部署后端实际上进行了一个代理模式。
目前我理解的是这样的:
服务器对外开放端口为80; 你的项目运行在 5555 端口; 当你的浏览器访问, 服务器80 端口, 服务器会将数据转发到 5555 端口。 这样会解决跨域问题, 因为本质还是自己给自己发。
(小白理解有问题请大家留言指正)
文件配置实际上和前端差不多也是写在server中, 有多个就写多个server , 我的是有两个,所以写两个server,写在http中。
# 客户端接口 server{ listen 80; server_name 123.56.223.123; location /{ proxy_pass http://127.0.0.1:5555; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } # 后台接口 server{ listen 8000; server_name 123.56.223.123; location /{ proxy_pass http://127.0.0.1:5558; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
设置完后重启nginx
nginx -s reload
在这里你要切记检查自己对外开放的接口是否开启, 推荐检测方式。
curl ip:端口
[D:\~]$ curl 123.56.223.123:8000
# 这种情况说明为开启
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- 0:00:21 --:--:-- 0
curl: (28) Failed to connect to 123.56.223.123 port 8000: Timed out
[D:\~]$ curl 123.56.223.123:8000
# 这种情况说明开启了
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 182 100 182 0 0 1421 0 --:--:-- --:--:-- --:--:-- 1421
<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.14.0 (Ubuntu)</center>
</body>
</html>
# 也可用
telnet ip 端口
开启方式:
我是用阿里云,最简单的就是在控制台开启。
而项目运行,可以采用 uwsgi 或者 gunicorn,
我的后台是5558 端口,所以我直接运行在这个端口
gunicorn --log-level=info -b 0.0.0.0:5558 'app:dash()'