启动 Gunicorn 失败

Failed to start Gunicorn

正在尝试在 ubuntu 上部署 Django 应用程序。

开始-server.sh有

cd /home/django
source env/bin/activate
cd tutorial
gunicorn tutorial.wsgi

如果我bash开始-server.sh一切运行都很好。

所以,我写了下面的东西。

gunicorn.service 保存在 /etc/systemd/system/ 看起来像

[Unit]
Description=Gunicorn
After=network.target

[Service]
Type=simple
User=django
ExecStart=/bin/bash /home/django/bin/start-server.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target

然后我运行

 sudo systemctl enable gunicorn
 sudo systemctl start gunicorn

但现在我看到 502 错误。当我 bash 开始-server.sh 时,一切都很完美。但是,不知何故,gunicorn 无法正常工作。

guincorn 版本 18.0(我试过 20.0 但没有成功)

sudo systemctl status gunicorn 显示

● gunicorn.service - Gunicorn
     Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Wed 2021-06-09 16:56:59 UTC; 2min 5s ago
   Main PID: 26285 (code=exited, status=126)

Jun 09 16:56:58 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Main process exited, code=exited, status=126/n/a
Jun 09 16:56:58 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Failed with result 'exit-code'.
Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Scheduled restart job, restart counter is at 5.
Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: Stopped Gunicorn.
Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Start request repeated too quickly.
Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Failed with result 'exit-code'.
Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: Failed to start Gunicorn.

不要在您的 bash 脚本中执行 cd-命令,而是使用完整路径

source /home/django/env/bin/activate
gunicorn /home/django/env/bin/activate/tutorial.wsgi

start-server.sh 之上添加以下行:

#!/bin/bash

这称为“shebang”行。类 Unix 系统通常不注意文件扩展名,因此忽略文件名以 .sh 结尾的事实。系统查看这一行以确定文件将由 bash.

执行

此外,您需要确保文件是可执行的:

chown +x /home/django/bin/start-server.sh

然而,你真的根本不需要start-server.sh,因为它所做的一切都可以由 systemd 完成。将此行添加到 [Service] 部分:

WorkingDirectory=/home/django/tutorial

并将 ExecStart 替换为:

ExecStart=/home/django/env/bin/gunicorn tutorial.wsgi

就是这样。如果您觉得它令人困惑,请阅读 virtualenv demystified.