正如@chris-wheadon 在他的评论中建议的那样,您应该尝试在后台运行 celery 作为守护进程。AWS Elastic Beanstalk 已经使用supervisord来运行一些守护进程。因此,您可以利用它来运行 celeryd 并避免为此创建自定义 AMI。它对我很有效。
我所做的是在 EB 将应用程序部署到实例后,以编程方式将 celeryd 配置文件添加到实例中。棘手的部分是该文件需要为守护程序设置所需的环境变量(例如,如果您在应用程序中使用 S3 或其他服务,则为 AWS 访问密钥)。
下面是我使用的脚本的副本,将此脚本添加到.ebextensions
配置 EB 环境的文件夹中。
安装脚本在所有 EB 实例上的/opt/elasticbeanstalk/hooks/appdeploy/post/
文件夹 (文档) 中创建一个文件。那里的任何 shell 脚本都将在部署后执行。放置在那里的 shell 脚本的工作方式如下:
- 在
celeryenv
变量中,virutalenv 环境以遵循 supervisord 表示法的格式存储。这是一个逗号分隔的环境变量列表。
- 然后脚本创建一个变量
celeryconf
,其中包含配置文件作为字符串,其中包括先前解析的 env 变量。
- 然后将该变量通过管道传输到一个名为 的
celeryd.conf
文件中,该文件是 celery 守护进程的 supervisord 配置文件。
- 最后,新创建的配置文件的路径被添加到主
supervisord.conf
文件中,如果它不存在的话。
这是脚本的副本:
files:
"/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh":
mode: "000755"
owner: root
group: root
content: |
#!/usr/bin/env bash
# Get django environment variables
celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'`
celeryenv=${celeryenv%?}
# Create celery configuraiton script
celeryconf="[program:celeryd]
; Set full path to celery program if using virtualenv
command=/opt/python/run/venv/bin/celery worker -A myappname --loglevel=INFO
directory=/opt/python/current/app
user=nobody
numprocs=1
stdout_logfile=/var/log/celery-worker.log
stderr_logfile=/var/log/celery-worker.log
autostart=true
autorestart=true
startsecs=10
; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600
; When resorting to send SIGKILL to the program to terminate it
; send SIGKILL to its whole process group instead,
; taking care of its children as well.
killasgroup=true
; if rabbitmq is supervised, set its priority higher
; so it starts first
priority=998
environment=$celeryenv"
# Create the celery supervisord conf script
echo "$celeryconf" | tee /opt/python/etc/celery.conf
# Add configuration script to supervisord conf (if not there already)
if ! grep -Fxq "[include]" /opt/python/etc/supervisord.conf
then
echo "[include]" | tee -a /opt/python/etc/supervisord.conf
echo "files: celery.conf" | tee -a /opt/python/etc/supervisord.conf
fi
# Reread the supervisord config
supervisorctl -c /opt/python/etc/supervisord.conf reread
# Update supervisord in cache without restarting all services
supervisorctl -c /opt/python/etc/supervisord.conf update
# Start/Restart celeryd through supervisord
supervisorctl -c /opt/python/etc/supervisord.conf restart celeryd