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()'