Search code examples
pythonnginxflaskgunicorn

how to make my python-flask website available 24*7 using nginx and gunicorn


How to configure gunicorn to make sure my python-flask website is available 24*7 ? The issue I am facing is: As soon I kill my terminal window, the website is no more reachable.

I am using rhel7.6 to host a website using python-flask. I have configured nginx as the web server and gunicorn as the application server.

. I will really appreciate if some one can help me in using/configuring gunicorn to make sure my website is available 24*7.

Please have some of my code as below:

[root@syed-dashboard-4 ~]# pwd
/root
[root@syed-dashboard-4 ~]#
[root@syed-dashboard-4 ~]# cat hello.py
#!/usr/bin/python

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
        return "Hello magentabox!"

#if __name__ == "__main__":
#        app.run(host='10.145.29.23',port=5000)

[root@syed-dashboard-4 ~]#
[root@syed-dashboard-4 ~]# gunicorn hello:app
[2019-07-17 10:34:11 +0000] [9346] [INFO] Starting gunicorn 19.9.0
[2019-07-17 10:34:11 +0000] [9346] [INFO] Listening at: http://127.0.0.1:8000 (9346)
[2019-07-17 10:34:11 +0000] [9346] [INFO] Using worker: sync
[2019-07-17 10:34:11 +0000] [9351] [INFO] Booting worker with pid: 9351

I am pretty new to web development and as I mentioned as soon I close the terminal, the website is no more reachable. I can share the nginx configuration logs as well if that helps fixing my issue. Thanks much.


Solution

  • You can use the supervisor. This is the professional way to run your server for 24*7. Please add below file in your supervisor config to run.

    [program:your_project_name]
    command=/home/virtualenvpath/your_env/bin/gunicorn --log-level debug run_apiengine:main_app --bind 0.0.0.0:5006 --workers 5 --worker-class gevent
    stdout_logfile=/home/your_path_to_log/supervisor_stdout.log
    stderr_logfile=/home/your_path_to_log/supervisor_stderr.log
    user=your_user
    autostart=true
    autorestart=true
    environment=PYTHONPATH="$PYTHONPATH:/home/path_to_your_project";OAUTHLIB_INSECURE_TRANSPORT='1';
    

    Configure this in supervisor it will run for 24*7. And whenever your machine restarts it will auto start.