在生產環境中部署Django、Celery項目需要開機啟動,因此需要配置系統服務。
下面以CentOS7系統為例,記錄配置Django和Celery為系統服務,並開機啟動。
1.Django服務
在生產環境中部署Django項目需要用到uwsgi或gunicorn,這里我使用gunicorn。
1.1 Gunicorn簡介
Gunicorn“綠色獨角獸”是一個被廣泛使用的高性能的Python WSGI UNIX HTTP服務器,移植自Ruby的獨角獸(Unicorn )項目,使用pre-fork worker模式,具有使用非常簡單,輕量級的資源消耗,以及高性能等特點。
Gunicorn 服務器作為wsgi app的容器,能夠與各種Web框架兼容(flask,django等),得益於gevent等技術,使用Gunicorn能夠在基本不改變wsgi app代碼的前提下,大幅度提高wsgi app的性能。
1.2 安裝Gunicorn
pip3 install gunicorn
1.3 靜態文件處理
# urls.py中增加
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
2.配置Django服務
編寫/usr/lib/systemd/system/django.service
[Unit] Description=django daemon service After=network.target [Service] WorkingDirectory=/opt/Django-Project # Django項目路徑 ExecStart=/usr/local/bin/gunicorn --workers 3 --bind 0.0.0.0:8000 Django-Project-Name.wsgi:application [Install] WantedBy=multi-user.target
3.配置Celery服務
3.1 Celery目錄
創建celery log目錄 /var/log/celery/
創建celery pid目錄 /opt/celery/
3.2 Celery配置文件
創建celery配置文件/etc/conf.d/celery
# Name of nodes to start # here we have a single node CELERYD_NODES="w1" # or we could have three nodes: #CELERYD_NODES="w1 w2 w3" # Absolute or relative path to the 'celery' command: CELERY_BIN="/usr/local/bin/celery" #CELERY_BIN="/virtualenvs/def/bin/celery" # App instance to use # comment out this line if you don't use an app
CELERY_APP="proj" # 這里修改為Django項目名稱 # How to call manage.py CELERYD_MULTI="multi" # Extra command-line arguments to the worker CELERYD_OPTS="--time-limit=300 --concurrency=4" # - %n will be replaced with the first part of the nodename. # - %I will be replaced with the current child process index # and is important when using the prefork pool to avoid race conditions. CELERYD_PID_FILE="/opt/celery/%n.pid" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_LOG_LEVEL="INFO" # you may wish to add these options for Celery Beat CELERYBEAT_PID_FILE="/opt/celery/beat.pid" CELERYBEAT_LOG_FILE="/var/log/celery/beat.log"
3.3 Celery systemd unit
編寫/usr/lib/systemd/system/celery.service
[Unit] Description=Celery Service After=network.target [Service] Type=forking EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/opt/Djang-Project # Django項目路徑 ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \
-A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \
--pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \
-A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target
4.啟動服務
systemctl enable --now django.service
systemctl enable --now celery.service
參考文章:
https://docs.celeryproject.org/en/stable/userguide/daemonizing.html
https://www.howtoforge.com/how-to-install-django-on-centos-8/