我正在按照这个(非常好的)DigitalOcean 教程了解如何使用 Gunicorn 提供 Flask 应用程序,但无法让 Systemd 运行myproject.service
。
我创建了一个 python 环境 (venv),pip 安装了 gunicorn 和 flask,编写了 myproject.py 和 wsgi.py,并检查所有程序是否可执行。当我运行以下命令时:
(venv) dconran@dconran-VirtualBox:~/python/dg$ /home/dconran/python/dg/venv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 wsgi:app
从命令行,无论是在 Python 环境中还是在停用后,一切都运行正常,我可以访问网页。但是当我运行sudo systemctl start myproject
当我这样做时,我收到以下错误消息sudo systemctl status myproject
:
× myproject.service - Gunicorn instance to serve myproject
Loaded: loaded (/etc/systemd/system/myproject.service; enabled; preset: enabled)
Active: failed (Result: exit-code) since Fri 2025-02-14 12:40:11 GMT; 23s ago
Duration: 12ms
Main PID: 6526 (code=exited, status=2)
CPU: 5ms
Feb 14 12:40:11 dconran-VirtualBox systemd[1]: Started myproject.service - Gunicorn instance to serve myproject.
Feb 14 12:40:11 dconran-VirtualBox bash[6527]:
/home/dconran/python/dg/venv/bin/gunicorn: line 3: import: command not found
Feb 14 12:40:11 dconran-VirtualBox bash[6528]:
/home/dconran/python/dg/venv/bin/gunicorn: line 4: import: command not found
Feb 14 12:40:11 dconran-VirtualBox bash[6529]:
/home/dconran/python/dg/venv/bin/gunicorn: line 5: from: command not found
Feb 14 12:40:11 dconran-VirtualBox bash[6526]:
/home/dconran/python/dg/venv/bin/gunicorn: line 7: syntax error near unexpected token `('
Feb 14 12:40:11 dconran-VirtualBox bash[6526]:
/home/dconran/python/dg/venv/bin/gunicorn: line 7: ` sys.argv[0] = re.sub(r'(-script\.>
Feb 14 12:40:11 dconran-VirtualBox systemd[1]: myproject.service: Main process exited,
code=exited, status=2/INVALIDARGUMENT
Feb 14 12:40:11 dconran-VirtualBox systemd[1]: myproject.service: Failed with result
'exit-code'.
myproject.service
包括:-
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target
[Service]
User=dconran
Group=www-data
WorkingDirectory=/home/dconran/python/dg
Environment="PATH=/home/dconran/python/dg/venv/bin"
ExecStart=/usr/bin/bash /home/dconran/python/dg/venv/bin/gunicorn --workers 3 --bind
unix:myproject.sock -m 007 wsgi:app
[Install]
WantedBy=multi-user.target
我已经确认 python3 和 gunicorn 都在 ...venv/bin 中,并且事实上,从命令行运行时 gunicorn 确实可以正常运行 - 那么为什么它不能通过 systemd 运行呢?
如有任何帮助/建议,我们将不胜感激。
您的服务正在尝试运行该命令:
但这
gunicorn
不是 Bash 脚本。这是 Python 脚本。错误消息来自 Bash 尝试将 Python 的每一行解释为 shell 命令。要么指定正确的解释器(
python
),要么根本不指定解释器——该文件已被标记为“可执行”并具有适当的#!
行,这意味着可以告诉操作系统直接执行它(并且会自动运行必要的解释器而无需您指定它)......就像您手动启动 gunicorn 时所做的一样。bash <file>
(还要注意,和之间是有区别的bash -c "<command>"
。前者将指定路径的内容解释为 shell 命令;后者将路径本身解释为 shell 命令——所以我猜你可能一直在考虑bash -c /path/to/gunicorn
,这几乎可以奏效,但实际上是多余的,因为无论如何你都可以在没有 bash 的情况下运行 gunicorn。)