溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Django+Gunicorn+Nginx如何部署

發(fā)布時(shí)間:2021-08-21 11:02:43 來(lái)源:億速云 閱讀:130 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹Django+Gunicorn+Nginx如何部署,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

部署

網(wǎng)上有很多都是用 UWSGI 的方式來(lái)部署,但是我個(gè)人比較喜歡 Gunicorn,所以以下內(nèi)容我只是記錄了 Django + Gunicorn + Nginx 在 Ubuntu 上的部署方式相關(guān)內(nèi)容。

步驟一

上傳網(wǎng)站源碼至目標(biāo)服務(wù)器

由于我的源碼是用 Github 來(lái)托管的,所以我直接執(zhí)行下述命令來(lái)克隆我的網(wǎng)站源碼到服務(wù)器即可。

git clone https://github.com/your-name/repo-name.git

# 進(jìn)入項(xiàng)目目錄
cd repo-name

# 創(chuàng)建并激活虛擬環(huán)境
python3 -m virtualenv venv
source venv/bin/activate

# 安裝項(xiàng)目依賴
pip install -r requirements.txt

目前我的網(wǎng)站采用的相關(guān)依賴包如下:

autopep8
Django
django-bootstrap4
django-ckeditor
gunicorn
Markdown
Pillow
python-slugify
requests

這里有個(gè)坑需要注意,如果你使用了 awesome-slugify,請(qǐng)嘗試使用 python-slugify,因?yàn)橛械姆?wù)器可能無(wú)法正常安裝 awesome-slugify,具體 BUG 可參考:Clashes with python-slugify package。

步驟二

修改項(xiàng)目相關(guān)配置,并進(jìn)行靜態(tài)資源收集

由于我需要將我的網(wǎng)站部署到生產(chǎn)環(huán)境,所以我需要關(guān)閉 Django 的調(diào)試模式,并修改靜態(tài)資源相關(guān)配置,示例配置如下所示:

settings.py

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

DEBUG = os.environ.get('DJANGO_DEBUG', False)

TEMPLATE_DEBUG = os.environ.get('DJANGO_TEMPLATE_DEBUG', False)

ALLOWED_HOSTS = ["*"]

TEMPLATES = [
  {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
      'context_processors': [
        'django.template.context_processors.debug',
        'django.template.context_processors.request',
        'django.contrib.auth.context_processors.auth',
        'django.contrib.messages.context_processors.messages',
      ],
    },
  },
]

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
  os.path.join(BASE_DIR, 'static'),
]

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

然后執(zhí)行如下命令進(jìn)行靜態(tài)資源收集:

python manage.py collectstatic

之后,我還需要?jiǎng)?chuàng)建一個(gè) Gunicorn 進(jìn)程的相關(guān)配置,示例配置如下所示:

gunicorn.conf.py

# 安裝
# sudo pip3 install gunicorn

import sys
import os
import logging
import logging.handlers
from logging.handlers import WatchedFileHandler
import multiprocessing

BASE_DIR = '/home/hippie/hippiezhou.fun/src'
sys.path.append(BASE_DIR)

LOG_DIR = os.path.join(BASE_DIR, 'log')
if not os.path.exists(LOG_DIR):
  os.makedirs(LOG_DIR)

# 綁定的ip與端口
bind = "0.0.0.0:8000"

# 以守護(hù)進(jìn)程的形式后臺(tái)運(yùn)行
daemon = True

# 最大掛起的連接數(shù),64-2048
backlog = 512

# 超時(shí)
timeout = 30

# 調(diào)試狀態(tài)
debug = False

# gunicorn要切換到的目的工作目錄
chdir = BASE_DIR

# 工作進(jìn)程類(lèi)型(默認(rèn)的是 sync 模式,還包括 eventlet, gevent, or tornado, gthread, gaiohttp)
worker_class = 'sync'

# 工作進(jìn)程數(shù)
workers = multiprocessing.cpu_count()

# 指定每個(gè)工作進(jìn)程開(kāi)啟的線程數(shù)
threads = multiprocessing.cpu_count() * 2

# 日志級(jí)別,這個(gè)日志級(jí)別指的是錯(cuò)誤日志的級(jí)別(debug、info、warning、error、critical),而訪問(wèn)日志的級(jí)別無(wú)法設(shè)置
loglevel = 'info'

# 日志格式
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'
# 其每個(gè)選項(xiàng)的含義如下:
'''
h     remote address
l     '-'
u     currently '-', may be user name in future releases
t     date of the request
r     status line (e.g. ``GET / HTTP/1.1``)
s     status
b     response length or '-'
f     referer
a     user agent
T     request time in seconds
D     request time in microseconds
L     request time in decimal seconds
p     process ID
'''

# 訪問(wèn)日志文件
accesslog = os.path.join(LOG_DIR, 'gunicorn_access.log')
# 錯(cuò)誤日志文件
errorlog = os.path.join(LOG_DIR, 'gunicorn_error.log')
# pid 文件
pidfile = os.path.join(LOG_DIR, 'gunicorn_error.pid')

# 訪問(wèn)日志文件,"-" 表示標(biāo)準(zhǔn)輸出
accesslog = "-"
# 錯(cuò)誤日志文件,"-" 表示標(biāo)準(zhǔn)輸出
errorlog = "-"

# 進(jìn)程名
proc_name = 'hippiezhou_fun.pid'

# 更多配置請(qǐng)執(zhí)行:gunicorn -h 進(jìn)行查看

之后可用通過(guò)如下方式啟動(dòng)我們的網(wǎng)站:

# 啟動(dòng)方式(首先需要切換到項(xiàng)目根目錄,即和 manage.py 在同級(jí)目錄下):

gunicorn -c gunicorn.conf.py website.wsgi:application

# 或
gunicorn website.wsgi:application -b 0.0.0.0:8000 -w 4 -k gthread

# 或
gunicorn website.wsgi:application -b 0.0.0.0:8000 -w 4 -k gthread --thread 40 --max-requests 4096 --max-requests-jitter 512

# 查看進(jìn)程
ps aux | grep gunicorn

步驟三

配置 Nginx

通過(guò)前兩步,我們可以成功將我們的網(wǎng)站跑起來(lái),但是目前還只能在內(nèi)部訪問(wèn),所以我們需要通過(guò) Nginx 來(lái)做反向代理,供外網(wǎng)訪問(wèn)。

執(zhí)行下述命令進(jìn)行安裝和配置

sudo apt-get install nginx

sudo service nginx start

# 備份默認(rèn)配置
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak

# 啟動(dòng) Vim 修改我們的網(wǎng)站配置
sudo vim /etc/nginx/sites-available/default

示例配置如下所示:

server{
    ...
    server_name hippiezhou.fun *.hippiezhou.fun;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    ...

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        # try_files $uri $uri/ =404;
        proxy_pass     http://127.0.0.1:8000; #此處要和你 gunicore 的 ip 和端口保持一致
        proxy_redirect   off;

        proxy_set_header  Host         $host;
        proxy_set_header  X-Real-IP      $remote_addr;
        proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header  X-Forwarded-Proto  $scheme;
    }

    location /static {
        alias /root/hippiezhou.fun/src/staticfiles; # 此次需要配置為你的網(wǎng)站對(duì)應(yīng)的靜態(tài)資源的絕對(duì)路徑
    }

    location /media {
        alias /root/hipiezhou.fun/src/media; # 如果你的網(wǎng)站有上傳功能,需要配置該結(jié)點(diǎn)并指向目標(biāo)路徑
    }

    ...
}

配置完成后執(zhí)行下述操作即可將我們的網(wǎng)站運(yùn)行起來(lái)

# 若網(wǎng)站未啟動(dòng)執(zhí)行該命令
gunicorn -c gunicorn.conf.py website.wsgi:application

sudo nginx -t
sudo service nginx restart

如果不出意外,網(wǎng)站應(yīng)該是可以正常訪問(wèn),如果靜態(tài)資源依然不能訪問(wèn),打開(kāi)網(wǎng)站的 開(kāi)發(fā)者工具看一下是什么錯(cuò)誤。

  • 如果是 404 的問(wèn)題,請(qǐng)確保你的 settings 相關(guān)配置和我上面列出來(lái)的是一致的;

  • 如果是 403 的問(wèn)題,應(yīng)該是 Nginx 無(wú)權(quán)訪問(wèn)你指定的靜態(tài)資源,你需要修改 Nginx 的用戶類(lèi)型,親執(zhí)行下述命令

sudo vim /etc/nginx/nginx.conf

將 user 后面的值修改為 root,然后重啟 Nginx 即可。

最后,關(guān)于如何配置 HTTPS,這里就不過(guò)多介紹了,直接列出相關(guān)示例腳本:

sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository universe
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot python-certbot-nginx

sudo certbot --nginx

# sudo certbot renew --dry-run

sudo ufw allow https

sudo systemctl restart nginx

以上是“Django+Gunicorn+Nginx如何部署”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)
推薦閱讀:
  1. sybase部署
  2. Django部署

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI