Centos7.X Django+uwsgi+nginx配置

1.安裝

pip install uwsgi django

nginx安裝請參考其他博文

安裝的uwsgi創建一個全局環境的命令:

ln -s /usr/local/python3/bin/uwsgi /usr/bin/

2.配置

1.新建一個名字爲test的django項目

python3 -m django startproject /var/www/test

2.在test項目中創建一個名字爲index的app

cd test && python3 manage.py startapp index

note:如果創建App時提示由於沒有 No module named '_sqlite3' 的錯誤,可以先下載 SQLite 數據庫。或者將test項目的數據庫修改爲已有的數據庫,例如mysql數據庫,修改test中的文件settings.py

如果提示沒有mysqlclient,則需要安裝 pip install pymysql然後修改django目錄下的__init__.py 添加: import pymysql ,  pymysql.install_as_MySQLdb()

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

修改爲:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test123',#要在mysql中先創建一個test123的數據庫:create database test123 character set utf8mb4 collate utf8mb4_unicode_ci;
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST':'localhost',
    }
}

修改完成後,再創建一個app

3.測試django項目是否能夠正常運行

python3 manage.py runserver 0.0.0.0:9876

用外網ip:9876或localhost:9876的形式訪問,能訪問成功說明django項目可以正常運行

如果訪問的時候出現了 

You may need to add '*.*.*.*' to ALLOWED_HOSTS.

則修改settings.py中的 ALLOWED_HOSTS = ['*'] 保存刷新再訪問即可

4.配置uwsgi

關掉剛剛測試的django項目,Ctrl+C

新建一個uwsgi.ini文件,內容如下:

[uwsgi]

socket = 127.0.0.1:8099
chdir           = /var/www/test
module          = test.wsgi
master          = true
processes       = 4
vacuum          = true
daemonize       = /var/log/uwsgi_log.log

執行: uwsgi --ini uwsgi.ini

[uWSGI] getting INI configuration from uwsgi.ini

出現上面的信息則uwsgi開啓成功,可以通過netstat -nultp 看到uwsgi監聽了內網的8099端口

5.配置Nginx

打開nginx的配置文件,nginx.conf 修改爲如下:

其中static是用來存放靜態文件,其他的請求都轉發到8099端口上,uwsgi監聽着8099端口,收到nginx發來的請求之後交給django處理,最後再由uwsgi把返回的內容給nginx,nginx響應。

nginx在其中充當着反向代理的功能。

    server {
        listen       80;
        server_name  localhost;

		location /static {
            alias /var/www/static;
        }

        location / {
            uwsgi_pass  127.0.0.1:8099;
            include     /usr/local/nginx/conf/uwsgi_params;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

6.完成

可以通過ip地址來訪問,若配置域名則可通過域名來訪問,邏輯層django處理,nginx爲一個代理服務器,uwsgi是web服務器

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