前后端分離項目的部署主要使用Nginx和uwsgi來實現,把Nginx換成Apache也是可以的,看個人喜好。Nginx主要處理靜態文件,uwsgi用來部署Django項目,處理其他請求
安裝uwsgi:
pip3 install uwsgi
測試uwsgi:
首先創建一個test.py文件
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"]
在文件目錄下使用命令:
uwsgi --http :80 --wsgi-file test.py
訪問我們的網站,能夠得到Hello World,則uwsgi安裝成功
部署django項目:
為了以后使用方便,可先創建一個目錄存放uwsgi配置文件
mkdir website_uwsgi
cd website_uwsgi
vim uwsgi.ini
配置文件內容如下
[uwsgi]
chdir = /home/iot/IOTPlatform #項目根目錄
module = IOTPlatform.wsgi:application # wsgi
http = :8000
master = True
Processes = 4 #最大進程數
harakiri = 60 #
max-requests = 5000
# socket = 127.0.0.1:8000
uid = 1000
gid = 2000
pidfile = /home/iot/website_uwsgi/master.pid
daemonize = /home/iot/website_uwsgi/mysite.log
vacuum = True
部分選項的含義:
chdir : 項目根目錄路徑
module: 入口文件
http:監聽的IP和端口,socket也是,如果使用Nginx做反向代理就應該選擇socket方式,因為nginx反向代理使用的是socket方式,在這個項目中沒有使用方向代理所以選用了http的方式
master:是否啟動主進程
processes: 設置進程數目
harakiri: 請求超時時間
max-requests:每個工作進程設置請求數的上限
pidfile:指定pid文件
daemonize: 日志文件
uwsgi配置文件寫好了,使用命令啟動:
uwsgi --ini uwsgi.ini
啟動完成之后,使用ps -aux | grep uwsgi 查看是否有4個進程來判斷uwsgi是否啟動成功,另外可以使用接口工具訪問接口看是否有正常的數據
其他的一些命令:
uwsgi --reload master.pid 重啟服務
uwsgi --stop master.pid 停止服務
部署靜態文件:
靜態文件有兩種方式
1:通過django路由訪問
2:通過nginx直接訪問
方式1:
需要在根目錄的URL文件中增加 url(r'^$', TemplateView.as_view(template_name="index.html")),作為入口,在setting中更改靜態資源位置
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "dist/static"), # 靜態文件目錄位置
)
方式2:
安裝nginx: apt-get install nginx
配置nginx: cd /etc/nginx
首先在 nginx的可用配置目錄下新建我們的配置文件
cd sites-available/
vim mysite.conf
server {
listen 80;
server_name iotplatform;
charset utf-8;
client_max_body_size 75M;
location /static {
alias /home/iot/IOTPlatform/dist/static;
}
location /media {
alias /home/iot/media;
}
location / {
root /home/iot/IOTPlatform/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
}
再使用命令測試我們的配置文件是否有問題
ln -s /etc/nginx/sites-available/mysite.conf /etc/nginx/sites-enabled/mysite.conf
nginx -t
沒有問題使用 service nginx restart重啟nginx服務,這樣就能訪問到靜態文件了
關於反向代理的問題
反向代理的配置文件:
server {
listen 80;
server_name iotplatform;
charset utf-8;
client_max_body_size 75M;
location /static {
alias /home/iot/IOTPlatform/dist/static
}
location /media {
alias /home/iot/media
}
location / {
uwsgi_pass 127.0.0.1:8000;
include /etc/nginx/uwsgi_params;
}
}
使用nginx -t測試的時候出現
nginx: [emerg] open() "/etc/nginx/conf/uwsgi_params" failed (2: No such file or directory) in /etc/nginx/nginx.conf:81
nginx: configuration file /etc/nginx/nginx.conf test failed
提示說沒有找到uwsgi_params文件我的解決方法是:手動新建一個conf目錄並將uwsgi_params文件復制過去