詳解Django+uwsgi+Nginx上線最佳實戰

這篇文章主要介紹了Django+uwsgi+Nginx上線最佳實戰,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

什麼是uwsgi?

uWSGI是一個Web服務器,它實現了WSGI協議、uwsgi、http等協議。Nginx中HttpUwsgiModule的作用是與uWSGI服務器進行交換。WSGI是一種Web服務器網關接口。它是一個Web服務器(如nginx,uWSGI等服務器)與web應用(如用Flask框架寫的程序)通信的一種規範。

  1. WSGI是一種通信協議。
  2. uwsgi是一種線路協議而不是通信協議,在此常用於在uWSGI服務器與其他網絡服務器的數據通信。uwsgi協議是一個uWSGI服務器自有的協議,它用於定義傳輸信息的類型(type of information),每一個uwsgi packet前4byte爲傳輸信息類型描述,它與WSGI相比是兩樣東西。
  3. uWSGI是實現了uwsgi和WSGI兩種協議的Web服務器。

在開始之前

最小化安裝CentOS 6

備份網卡文件

~$ mkdir /etc/sysconfig/network-scripts/backup
~$ cp /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/network-scripts/backup/ifcfg-eth0.backup

配置阿里雲鏡像源

~$ mkdir /etc/yum.repos.d/old
~$ mv /etc/yum.repos.d/CentOS-* /etc/yum.repos.d/old/
~$ cd /etc/yum.repos.d/
~$ curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
~$ yum clean all && yum repolist all && yum update -y
~$ reboot

Python3.6.0

上傳Python-3.6.0.tar.xz

~$ rz

安裝依賴

yum install zlib* gcc openssl openssl-devel libffi-devel -y
yum install pcre pcre-devel pcre-static -y

解壓Python-3.6.0.tar.xz

~$ tar -xvf Python-3.6.0.tar.xz
~$ cd Python-3.6.0

修改部分源代碼

~$ vim Modules/Setup.dist
# 將該文件的204到209行部分代碼取消註釋,完成後如下所示:
# Socket module helper for socket(2)
_socket socketmodule.c

# Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
SSL=/usr/local/ssl
_ssl _ssl.c \
  -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
  -L$(SSL)/lib -lssl -lcrypto

# The crypt module is now disabled by default because it breaks builds

編譯安裝

~$ ./configure
~$ make -j
~$ make install
~$ cd
~$ rm -rf Python-3.6.0

防火牆

# 恢復默認配置
iptables -F
# 放通3306/8000/80端口
iptables -I INPUT -p tcp -m tcp --dport 3306 -j ACCEPT
iptables -I INPUT -p tcp -m tcp --dport 8000 -j ACCEPT
iptables -I INPUT -p tcp -m tcp --dport 80 -j ACCEPT
# 保存規則
/etc/init.d/iptables save

SELinux

關閉SELinux

~$ vim /etc/selinux/config
# 修改配置爲如下所示:
SELINUX=permissive

~$ reboot

數據庫

二進制方式安裝

# 查找相關舊文件並刪除
find / -name mysql
find / -name mariadb
# 移除全部相關包
rpm -qa | grep mysql
rpm -qa | grep mariadb
# 添加用戶
useradd mysql -s /sbin/nologin -M
# 解壓移動文件
tar -xvf mysql-5.7.24-linux-glibc2.12-x86_64.tar.gz
mv mysql-5.7.24-linux-glibc2.12-x86_64 /applications/
ln -s /applications/mysql-5.7.24-linux-glibc2.12-x86_64/ /applications/mysql
# 創建配置文件
vim /etc/my.cnf
# 創建相關目錄
mkdir -p /data/mysql/data
mkdir -p /data/mysql/log
# 手動創建日誌文件
touch /data/mysql/log/mysqld.log
# 修改權限
chown -R mysql.mysql /applications/mysql
chown -R mysql.mysql /data/mysql

MySQL配置文件

[client]
port=3306
socket=/data/mysql/mysql.sock

[mysqld]
port=3306
datadir=/data/mysql/data
basedir=/applications/mysql
pid-file=/data/mysql/mysqld.pid
socket=/data/mysql/mysql.sock
user=mysql
character-set-server=utf8mb4
default-storage-engine=INNODB
collation-server = utf8mb4_general_ci
init_connect='SET NAMES utf8mb4'
max_connections = 1000
max_connect_errors = 1200
max_allowed_packet = 128M
explicit_defaults_for_timestamp = true
query_cache_size = 0
query_cache_type = 0
log_error = /data/mysql/log/error.log
slow_query_log = 1
slow_query_log_file = /data/mysql/log/slow.log
log_queries_not_using_indexes = 1
log_throttle_queries_not_using_indexes = 5
long_query_time = 8
log_slow_slave_statements = 1
min_examined_row_limit = 100
expire_logs_days = 5
tmpdir = /tmp
innodb_buffer_pool_size = 128M

[mysqld_safe]
log-error=/data/mysql/log/mysqld.log
pid-file=/data/mysql/mysqld.pid
# 同步數據
/applications/mysql/bin/mysql_install_db --basedir=/applications/mysql/ --datadir=/data/mysql/data/ --user=mysql

配置並啓動

cp /applications/mysql/support-files/mysql.server /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld 
vim /etc/init.d/mysqld
# 修改以下兩行
basedir=/applications/mysql
datadir=/data/mysql/data
# 查看是否啓動
netstat -tunlap | grep mysql
# 添加服務並設置爲開機自啓動
chkconfig --add mysqld
chkconfig mysqld on

初始化數據庫

/applications/mysql/bin/mysql_secure_installation
-- 設置用戶密碼
alter user 'root'@'localhost' identified by '123456';
-- 允許root遠程訪問
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;
FLUSH PRIVILEGES;

Django

配置pip3源

mkdir /root/.pip
touch /root/.pip/pip.conf
echo '[global]' >> /root/.pip/pip.conf
echo 'trusted-host=mirrors.aliyun.com' >> /root/.pip/pip.conf
echo 'index-url=https://mirrors.aliyun.com/pypi/simple/' >> /root/.pip/pip.conf

創建虛擬環境安裝依賴

# PublisherPro,一個支持MD輕量級的CMS程式.
git clone https://gitee.com/bluemiaomiao/PublisherPro.git
pip3 install virtualenv
cd PROJECT_DIR
virtualenv venv
source venv/bin/activate
pip3 install -r requestments.txt
pip3 install uwsgi
mkdir log
mkdir script
touch PublisherPro/script/uwsgi.pid
touch PublisherPro/script/uwsgi.status
vim uwsgi.ini

修改項目配置

# PROJECT_DIR/PROJECT_NAME/settings.py
# 設置爲生產環境
DEBUG = False
# 配置數據庫
DATABASES = {
 'default': {
  'ENGINE': 'django.db.backends.mysql',
  'NAME': 'publisher_pro',
  'USER': 'pubpro',
  'PASSWORD': 'bluemiaomiao',
  'HOST': '192.168.1.203',
  'PORT': '3306',
  'OPTIONS': {'init_command': 'SET default_storage_engine=INNODB;'},
 }
}
# 配置靜態文件相關
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

創建數據庫和用戶

CREATE DATABASE `publisher_pro` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
CREATE USER `pubpro`@`localhost` IDENTIFIED BY 'bluemiaomiao' PASSWORD EXPIRE NEVER;
CREATE USER `pubpro`@`%` IDENTIFIED BY 'bluemiaomiao' PASSWORD EXPIRE NEVER;
GRANT All ON `publisher\_pro`.* TO `pubpro`@`%`;

同步數據庫

./venv/bin/python3 manage.py makemigrations
./venv/bin/python3 manage.py migrate
./venv/bin/python3 manage.py createsuperuser
./venv/bin/python3 manage.py collectstatic

uwsgi

配置文件內容

# uwsig使用配置文件啓動
[uwsgi]
# 項目目錄
chdir=/applications/website/PublisherPro
# 指定項目的application
module=PublisherPro.wsgi:application
# 指定sock的文件路徑  
socket=/applications/website/PublisherPro/script/uwsgi.sock
# 進程個數  
workers=5
pidfile=/applications/website/PublisherPro/script/uwsgi.pid
# 狀態文件
stats=/applications/website/PublisherPro/script/uwsgi.status
# 指定IP端口  
http=0.0.0.0:8000
# 指定靜態文件
static-map=/static=/applications/website/PublisherPro/static
# 啓動uwsgi的用戶名和用戶組
uid=pubpro
gid=pubpro
# 啓用主進程
master=true
# 自動移除unix Socket和pid文件當服務停止的時候
vacuum=true
# 序列化接受的內容,如果可能的話
thunder-lock=true
# 啓用線程
enable-threads=true
# 設置自中斷時間
harakiri=30
# 設置緩衝
post-buffering=4096
# 設置日誌目錄
daemonize=/applications/website/PublisherPro/log/uwsgi.log

創建用戶和組並修改權限

# 創建用戶
useradd pubpro -s /sbin/nologin -M
# 檢查結果
id pubpro
# 修改權限
chown -R pubpro.pubpro /applications/website/PublisherPro/
# 檢查結果
ll -d /applications/website/PublisherPro/

測試Django應用

# 啓動應用
uwsgi --ini uwsgi.ini
# 重載應用
uwsgi --reload script/uwsgi.pid
# 狀態信息
uwsgi --connect-and-read script/uwsgi.status
# 停止應用
uwsgi --stop script/uwsgi.pid

Nginx

server {
 listen 80;
 server_name 192.168.2.108;
 access_log /var/log/nginx/access.log main;
 charset utf-8;
 gzip_types text/plain application/x-javascript text/css text/javascript application/x-httpd-php application/json text/json image/jpeg image/gif image/png application/octet-stream;
 error_page 404 /404.html;
 error_page 500 502 503 504 /50x.html;

 # 指定項目路徑uwsgi
 location / {
    # 導入一個Nginx模塊他是用來和uWSGI進行通訊的
  include uwsgi_params; 
    # 設置連接uWSGI超時時間
  uwsgi_connect_timeout 30; 
    # 指定uwsgi的sock文件所有動態請求就會直接丟給他
  uwsgi_pass unix:/data/PublisherPro/script/uwsgi.sock; 
 }

 # 指定靜態文件路徑
 location /static/ {
  alias /data/PublisherPro/static;
  index index.html index.htm;
 }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章