Ubuntu18下Celery4.3.0守护进程化报错:No module named 'celery'
解决Celery守护进程与Apache WSGI的ModuleNotFoundError问题
看起来你遇到的核心矛盾是Apache的WSGI进程和Celery守护进程使用的Python环境不统一——你在ubuntu用户环境下安装的Celery,无法被Apache的www-data用户进程识别,同时守护进程的环境变量也没完全适配。下面分方向给出具体的解决步骤:
1. 修复Apache WSGI的Python环境适配
Apache默认调用系统级Python环境,而你通过pip3 install --user celery安装的Celery仅对ubuntu用户可见,www-data用户访问不到这个包。
方案A:用虚拟环境(推荐)
如果你的Django项目用了虚拟环境,直接在Apache站点配置里绑定虚拟环境:
- 打开你的Apache站点配置文件(比如
/etc/apache2/sites-available/examgap.conf),添加或修改:WSGIPythonHome /path/to/your/virtualenv WSGIPythonPath /var/www/html/examgap - 重启Apache生效:
sudo systemctl restart apache2
方案B:让Apache访问用户级Python包
若未使用虚拟环境,把ubuntu用户的Python包路径注入WSGI的加载路径:
- 先获取用户site-packages路径:运行
python3 -c "import site; print(site.getusersitepackages())",输出类似/home/ubuntu/.local/lib/python3.6/site-packages - 在项目的
wsgi.py开头添加:import sys sys.path.append('/home/ubuntu/.local/lib/python3.6/site-packages') - 重启Apache生效。
2. 调整Celery守护进程的环境配置
即使修改了WorkingDirectory,守护进程仍可能因环境变量缺失找不到Celery包:
步骤1:给celery.service添加PYTHONPATH
编辑/etc/systemd/system/celery.service,在[Service]段加入环境变量配置:
[Service] Type=forking User=ubuntu Group=ubuntu EnvironmentFile=/etc/conf.d/celery # 替换为你的项目路径和用户site-packages路径 Environment="PYTHONPATH=/var/www/html/examgap:/home/ubuntu/.local/lib/python3.6/site-packages" WorkingDirectory=/var/www/html/examgap ...
步骤2:用绝对Python路径调用Celery
避免PATH环境变量的坑,直接指定Python解释器运行Celery,修改/etc/conf.d/celery:
# 替换原CELERY_BIN配置 CELERY_BIN="/usr/bin/python3 /home/ubuntu/.local/bin/celery"
步骤3:重新加载systemd并重启Celery
sudo systemctl daemon-reload sudo systemctl restart celery.service
3. 权限检查收尾
确保Apache和Celery能正常访问项目文件:
- 调整项目目录权限:
sudo chown -R ubuntu:www-data /var/www/html/examgap - 添加可读权限:
sudo chmod -R 755 /var/www/html/examgap
完成以上操作后,重启Apache和Celery服务,应该就能解决ModuleNotFoundError: No module named 'celery'的问题了。
内容的提问来源于stack exchange,提问作者Owen
相关产品推荐
相关产品推荐

