How do you daemonize a Flask application?

Question:

I have a small application written in Python using Flask. Right now I’m running it under nohup, but I’d like to daemonize it. What’s the proper way of doing this?

Asked By: James

||

Answers:

There are several ways to deploy a Flask project. Deploying with gunicorn might be the easiest, install gunicorn and then:

gunicorn project:app --daemon

Although you probably want to use supervisor or something of that nature to monitor gunicorn (at the very least use --pid so you can reload/stop gunicorn easily).

Answered By: zeekay

If you have supervisor installed already, I think gunicorn would be a little redundant. The following is a flask.ini file that can be dropped in /etc/supervisord.d/ (then “supervisorctl reload” to reload the config and start the process).

command=/opt/flask/env0/bin/python /opt/flask/developer/FlaskWebServer.py
directory=/opt/flask
redirect_stderr=true
startsecs=5
autorestart=true
stdout_logfile=/opt/flask/flask.stdout.log
Answered By: user3116242

If you would like to supervise it and keep it persistent across reboots, you could use immortal

You could call it like this:

immortal -l /var/log/your-app gunicorn project:app

Or via run.yml, for example:

cmd: gunicorn project:app
cwd: /path/of/project
env:
    DEBUG: 1
    ENVIRONMENT: production
 log:
    file: /var/log/app.log
    age: 86400 # seconds
    num: 7     # int
    size: 1    # MegaBytes
    timestamp: true # will add timesamp to log
 stderr:
    file: /var/log/app-error.log
    age: 86400 # seconds
    num: 7     # int
    size: 1    # MegaBytes
    timestamp: true # will add timesamp to log
 user: www

More about immortal: https://immortal.run/about/

Answered By: nbari

I an running centos with systemd working for all my other services.
So I used the same for my flask app

Create a script sh with all my Flask settings

#!/bin/bash
# flask settings
export FLASK_APP=/some_path/my_flask_app.py
export FLASK_DEBUG=0

flask run --host=0.0.0.0 --port=80

Make this script as executable

chmod +x path/of/my/script.sh

Add a systemd service to call this script

/etc/systemd/system/
vim flask.service

[Unit]
Description = flask python command to do useful stuff

[Service]
ExecStart = path/of/my/script.sh

[Install]
WantedBy = multi-user.target

To finish, enable it at boot

systemctl enable flask.service

More info about systemd: https://www.tecmint.com/create-new-service-units-in-systemd/

Answered By: Vespucci75fr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.