无法用systemd django启动gunicorn

时间:2016-05-16 18:13:15

标签: django gunicorn systemd virtualenvwrapper

我是systemd的新手。刚刚安装了lubuntu16.04
我有以下systemd文件:

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=jcg
Group=jcg
WorkingDirectory=/home/jcg/venvs/baseball/baseball_stats
ExecStart=/home/jcg/.virtualenvs/baseball/bin/gunicorn -w 3 -b 0.0.0.0:8001 baseball_stats.wsgi

[Install]
WantedBy=multi-user.target

我收到此错误:

jcg@jcg-Inspiron-1011:/var/log$ systemctl status gunicorn
● gunicorn.service - gunicorn daemon
   Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2016-05-16 13:59:18 EDT; 9min ago
  Process: 681 ExecStart=/home/jcg/.virtualenvs/baseball/bin/gunicorn -w 3 -b 0.0.0.0:8001 baseball_stats.wsgi 
 Main PID: 681 (code=exited, status=200/CHDIR)

May 16 13:59:18 jcg-Inspiron-1011 systemd[1]: Started gunicorn daemon.
May 16 13:59:18 jcg-Inspiron-1011 systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CH
May 16 13:59:18 jcg-Inspiron-1011 systemd[1]: gunicorn.service: Unit entered failed state.
May 16 13:59:18 jcg-Inspiron-1011 systemd[1]: gunicorn.service: Failed with result 'exit-code'.

但如果我运行此gunicorn starts

(baseball) jcg@jcg-Inspiron-1011:~/venvs/baseball/baseball_stats$ /home/jcg/.virtualenvs/baseball/bin/gunicorn -w 3 -b 0.0.0.0:8001 baseball_stats.wsgi

我错过了什么或做错了什么?

2 个答案:

答案 0 :(得分:16)

对于未来的读者,我的问题是由于没有我的django应用程序所需的环境变量集引起的。 (settings.py读取环境)。从命令行调用gunicorn时,先前已设置该环境变量。

使用systemd时,gunicorn.service文件中需要以下内容:

  [Service]
  Environment=SECRET_KEY=secret

答案 1 :(得分:0)

执行以下操作
首先你要在系统中创建一个服务文件

$ sudo nano /etc/systemd/system/python_django.service

在服务中编写如下代码

[Unit]
Description = Python django service
After = network.target

[Service]
ExecStart = /etc/python/python_script.sh

[Install]
WantedBy = multi-user.target

然后在 python_script.sh 中使用以下脚本创建一个文件 /etc/python/

#!/bin/bash
/usr/bin/gunicorn --access-logfile - -c /etc/python/config/python_django.py  python.wsgi:application

然后授予该文件的权限

$ chmod +x python_script.sh

python_django.py中创建一个文件/etc/python/config,然后放入以下代码

command = '/usr/bin/gunicorn'
pythonpath = '/home/user/{python_dir}'
bind = '0.0.0.0:8000'
workers = 5
user = 'user'

然后运行这段代码

$ sudo systemctl enable python_django //it creates a symlink
$ sudo systemctl start python_django 
$ sudo systemctl status python_django 

现在您可以看到正在运行的服务。

只需检查 http://{ip}:8000 || $ curl "http://0.0.0.0:8000"

注意:请确保您的 gunicorn 文件存在于 /usr/bin/gunicorn 将其检查为 $ ls -l /usr/bin/gunicorn