Nginx 是一個(gè)高性能的HTTP和反向代理服務(wù)器瓦哎,也可以做IMAP/POP3/SMTP服務(wù)器砸脊。
什么是反向代理?就是可以監(jiān)聽指定的外部端口践剂,并將訪問請求轉(zhuǎn)發(fā)到內(nèi)部端口溉知。
Nginx的好處:
- 可以隱藏真實(shí)端口陨瘩。
- 可以通過轉(zhuǎn)發(fā)實(shí)現(xiàn)集群處理。
- 容易配置级乍!容易配置舌劳!容易配置! 比起Apache來玫荣,Nginx配置不要太輕松甚淡。
部署步驟
一. 環(huán)境準(zhǔn)備
1. 安裝必須的包
yum gcc-c++, libxml*
gcc-c++是編譯器,一般都已安裝捅厂。
libxml* 是 xml支持, uwsgi -x 通過xml文件啟動(dòng)項(xiàng)目贯卦。使用ini等文件啟動(dòng)方式, 可以不裝
2. 安裝Django
, 略
二、安裝 uWSGI
WSGI焙贷,全稱是
Web Server Gateway Interface
撵割,是為Python定義的Web服務(wù)器和Web應(yīng)用程序之間的接口。
1. 安裝Python的uwsgi擴(kuò)展包
pip install uwsgi
2. 配置uWSGI
假設(shè)
Django
的項(xiàng)目路徑為/var/www/mywebsite
辙芍,可以把uwsgi
配置文件放在/var/www/
目錄下啡彬, 文件內(nèi)容如下
<uwsgi>
<socket>127.0.0.1:8020</socket> <!-- 內(nèi)部端口,自定義 -->
<chdir>/home/www/mywebsite</chdir> <!-- 項(xiàng)目路徑 -->
<module>mywebsite.wsgi</module> <!-- 指定項(xiàng)目的wsgi程序名稱沸手,配置錯(cuò)誤也沒關(guān)系外遇,會(huì)自動(dòng)在項(xiàng)目路徑下找wsgi文件 -->
<processes>4</processes> <!-- 進(jìn)程數(shù) -->
<daemonize>uwsgi.log</daemonize> <!-- 日志文件 -->
</uwsgi>
3. 啟動(dòng)uWSGI
uWSGI可以多種方式啟動(dòng),例子中用的是 .xml 配置文件方式契吉。
uwsgi -x mywebsite.xml
三. 安裝Nginx
CentOS下可以直接使用
yum
安裝,例子中用的是下載安裝方式诡渴。
1. 安裝Nginx
cd /tmp
wget -c http://nginx.org/download/nginx-1.14.1.tar.gz
tar -zxvf nginx-1.14.1.tar.gz
cd nginx-1.14.1
./configure
make && make install
Nginx 的默認(rèn)安裝路徑為/usr/local/nginx
2. 配置Nginx
打開配置文件捐晶,路徑
/usr/local/nginx/conf/nginx.conf
菲语,添加如下內(nèi)容:
server {
listen 8020; # 監(jiān)聽外部訪問端口
server_name localhost:8020; # 主機(jī)名稱
charset utf-8;
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8997; # 外部訪問80就轉(zhuǎn)發(fā)到內(nèi)部的8997
}
location /static/ {
alias /var/www/mywebsite/static/; # 項(xiàng)目靜態(tài)路徑設(shè)置
}
}
3. 啟動(dòng)Nginx
啟動(dòng)前,先用
Nginx -t
自檢一遍惑灵,沒報(bào)錯(cuò)再正式啟動(dòng)
cd /usr/local/nginx/sbin
./nginx -t
方法1:進(jìn)程啟動(dòng)
# 啟動(dòng)進(jìn)程
./nginx
# 關(guān)閉進(jìn)程
pkill -9 nginx
方法2:服務(wù)啟動(dòng)
使用yum安裝自帶 nginx.service山上。如果是通過編譯方式安裝,需要手動(dòng)配置.service文件英支。
- 創(chuàng)建
nginx.service
文件
vim /usr/lib/systemd/system/nginx.xervice
- 添加以下內(nèi)容
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
- 啟動(dòng)服務(wù)
systemctl start nginx