LoginSignup
15
18

More than 3 years have passed since last update.

Gunicorn用のSystemdソケットとサービスファイルの作成

Posted at

Djangoで作成したアプリを動かすサーバー(Gunicorn)の起動および停止を堅牢な方法で行う。

  • systemdサービスとソケットファイルを作成する
  • Gunicornソケットは起動時に作成され、接続を待ち受ける。
    • 接続が発生すると、systemdは自動的にGunicornプロセスを起動して接続を処理する

Gunicorn用のsystemdソケットファイルを作成する

sudo権限でGunicorn用のsystemdソケットファイルを作成する

$ sudo vim /etc/systemd/system/gunicorn.socket
/etc/systemd/system/gunicorn.socket
[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn/socket

[Install]
WantedBy=sockets.target

Gunicorn用のsystemdサービスファイルをsudo権限で作成する。

このとき、サービスのファイル名は拡張子を除いてソケットのファイル名と一致する必要がある。

  • プロセスはすべての関連ファイルを所有しているため、プロセスの所有権を通常ユーザーアカウントに与える。
  • NginxがGunicornと簡単に通信ができるようにwww-dataグループにグループの所有権を与える。
$ sudo vim /etc/systemd/system/gunicorn.service

ExecStart=/home/ ubuntu / myprojectdir /bin/gunicorn/home/ ubuntu / myprojectdir /bin/gunicornwhich gunicornで表示されたパスにする。

/etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ ubuntu / myprojectdir
ExecStart=/home/ ubuntu / myprojectdir /bin/gunicorn -- access-logfile - -- workers 3 --bind unix:/run/gunicorn/socket myproject.wsgi

[Install]
WantedBy=multi-user.target

Gunicornソケットを起動して有効化する

これにより、起動時に/run/gunicorn/socketファイルが作成される。そのソケットに接続するとsystemdはそれを処理するためにgunicorn.serviceを自動的に起動する。

$ sudo systemctl start gunicorn.socket
$ sudo systemctl enable gunicorn.socket

プロセスが開始できたかどうかを確認する。

$ sudo systemctl status gunicorn.socket

Nginxの設定

upstream app_server{
    server 127.0.0.1:8000 fail_timeout=0;
}
server{
    listern 80;
    server_name <yourIPadress> or <domain>

    location = /favicon.ico { access_log off; log_not_found off;}

    location /static/ {
        root /home/ ubuntu / myprojectdir;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn/socket;
    }
}

出典

15
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
18