Start python flask webserver automatically after booting the system and keep it on till the end Start python flask webserver automatically after booting the system and keep it on till the end flask flask

Start python flask webserver automatically after booting the system and keep it on till the end


I'd like to suggest using supervisor, the documentation is here


for a very simple demo purpose, after you installed it and finish the set up, touch a new a file like this:

[program:flask_app]                                                                  command = python main.py                                      directory = /dir/to/your/app                            autostart = true                                                                autorestart = true

then

$ sudo supervisorctl update

Now, you should be good to go. The flask app will start every time after you boot you machine.(note: distribution package has already integrated into the service management infrastructure, if you're using others, see here)

to check whether you app is running:

$ sudo supervisorctl status

For production, you can use nginx+uwsgi+supervisor. The flask deployment documentation is here


One well documented solution is to use Gunicorn and Nginx server:

  1. Install Components and setup a Python virtualenv with dependencies
  2. Create the wsgi.py file :
from myproject import application    if __name__ == "__main__":         application.run()

That will be handled by Gunicorn :

gunicorn --bind 0.0.0.0:8000 wsgi
  1. Configure Gunicorn with setting up a systemd config file: /etc/systemd/system/myproject.service :
 [Unit]    Description=Gunicorn instance to serve myproject    After=network.target [Service]    User=sammy    Group=www-data    WorkingDirectory=/home/sammy/myproject    Environment="PATH=/home/sammy/myproject/myprojectenv/bin"    ExecStart=/home/sammy/myproject/myprojectenv/bin/gunicorn     --workers 3 --bind unix:myproject.sock -m 007 wsgi:app[Install]    WantedBy=multi-user.target
  1. Start the Gunicorn service at boot :
    sudo systemctl start myproject    sudo systemctl enable myproject