[PYTHON] Operate Gunicorn via Fabric

Enabled to start and restart the application running on Gunicorn on the server side. I learned that to stop the process, you can kill it by specifying the pid.

gunicorn.conf.py

usr/bin/python
gunicorn.conf.py

bind = "0.0.0.0:5000"
workers = 2
worker_class = 'sync'
max_requests = 1000
timeout = 30
keep_alive = 2
preload = True
daemon = True

start.sh

GUNICORN=/usr/bin/gunicorn
ROOT=/your/app/path
PID=/var/run/gunicorn/your.pid
APP=run:app

if [ -f $PID ]; then rm $PID; fi
    cd $ROOT
    source venv/bin/activate
    exec $GUNICORN -c $ROOT/gunicorn.conf.py –pid=$PID $APP

fabfile.py

#coding: utf-8
from fabric.api import run,env,local,settings
from fabric.operations import sudo
from fabric.context_managers import cd
import os
import subprocess

from fabric.api import env, run
env.use_ssh_config = True
env.hosts = ["your ip address"]
env.key_filename = "/root/.ssh/authorized_keys"
env.user = "username"
env.password = "password"


def start():
    with settings():
        with cd("/your/path"):
            sudo("""
            source start.sh
            """,pty=False)

def stop():
    with settings():
        pid = get_pid()
        sudo("kill {}".format(pid))

def restart():
    try:
        stop()
    except:
        print("There isn't pid")
    start()

Now you can reboot freely with fab start / stop / restart.

Note

This article is http://furodrive.com/en/2014/2/stop_and_start_gunicorn It was created based on.

Recommended Posts

Operate Gunicorn via Fabric
I couldn't daemonize gunicorn with Fabric
fabric