CentOS7 部署Django Celery
在生产环境中部署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/