How do you daemonize a Flask application?

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).


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/

Tags:

Python

Flask