# Centos 7 下部署Django + uWSGI + Nginx
## 環境:
Python: 3.6
Django: 2.1
OS: CentOS 7 x86_64
uwsgi: 2.0.17
## 安裝Python3.6
* 不要刪除自帶的python2.7,否則會出問題,因為centos許多軟件需要依賴系統自帶python
* 安裝依賴工具 yum install openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel mysql-devel gcc gcc-devel python-devel
* 下載 wget https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tgz
* 解壓 tar -zxvf Python-3.6.5.tgz
* 移動至規范的放軟件的目錄下 mv Python-3.6.5 /usr/local
* 安裝:
* cd /usr/local/Python-3.6.5/
* ./configure
* make
* make install
* 驗證
* python -V
* source /home/cosmic/py3.6env/bin/activate 進入虛擬環境
## 安裝uWSGI
* 安裝 pip install uwsgi
* 驗證
```
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello Django"]
```
```
uwsgi --http :8001 --wsgi-file test.py
```
瀏覽器訪問,網頁能顯示 Hello Django 那么就沒問題
* 如果安裝失敗
* deactivate 退出虛擬環境
* yum install -y python-devel
* easy_install uwsgi
## 安裝Nginx
* 配置源
vi /etc/yum.repos.d/nginx.repo 添加下面內容
```
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/mainline/centos/7/x86_64/
gpgcheck=0
enabled=1
```
gpkcheck=0 表示對從這個源下載的rpm包不進行校驗;
enable=1 表示啟用這個源。
* yum install nginx
* 啟動nginx:
systemctl start nginx
* 修改默認端口號(默認為80)
```
vim /etc/nginx/conf.d/default.conf
server {
listen 8089;
listen [::]:8089;
...
...
}
```
* systemctl restart nginx 重啟nginx,直接訪問http://ip:8089 能看到nginx的歡迎界面即可。
## 配置
配置uwsgi啟動django的參數
```
vim django_uwsgi.ini
[uwsgi]
# 通過uwsgi訪問django需要配置成http
# 通過nginx請求uwsgi來訪問django 需要配置成socket
# 9000 是django的端口號
socket = :9000
# web項目根目錄
chdir = /home/root/pydj/django_one
# module指定項目自帶的的wsgi配置文件位置
module = django_one.wsgi
# 允許存在主進程
master = true
# 開啟進程數量
processes = 3
# 服務器退出時自動清理環境
vacuum = true
```
## 配置nginx
```
vi /etc/nginx/conf.d/default.conf
# 在文件最后,新加一個server
server {
listen 8089;
listen [::]:8089;
server_name 127.0.0.1 192.168.10.114;
location / {
include /etc/nginx/uwsgi_params;
uwsgi_pass 127.0.0.1:9000;
}
location /index/ {
root /index/;
}
location /static{
alias /home/root/pydj/django_one/sign/static;
}
}
```
* 8089 是對外的端口號
* server_name nginx代理uwsgi對外的ip
* 127.0.0.1:9000 即當nginx收到8089端口的請求時,直接將請求轉發給 127.0.0.1:9000
## uwsgi啟動django
```
# 進入項目根目錄
/home/root/pydj/django_one
# 啟動
uwsgi --ini django_uwsgi.ini
```
## 重啟Nginx
systemctl restart nginx
secrtcrt
filiza
xshell
安裝
pip freeze > requirements.txt
Django==2.1.2
django-haystack==2.8.1
mysqlclient==1.3.13
pytz==2018.5
uWSGI==2.0.17.1
Whoosh==2.7.4
semanage port -l | grep http_port_t
# mysql可以被局域網任意主機訪問
mysql> use mysql;
mysql> update user set host = '%' where user = 'root';
mysql> select host, user from user;
mysql> flush privileges;
* 修改setting文件之后
* python manage.py collectstatic 收集admin靜態文件
* 修改uwsgi.ini
* 啟動
* uwsgi --ini django_uwsgi.ini --buffer-size 32768
* 添加nginx配置文件
* 重啟nginx
*