Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Flask Server in the background

I have set up Flask on my Rapsberry Pi and I am using it for the sole purpose of acting as a server for an xml file which I created with a Python script to pass data to an iPad app (iRule).

My RPI is set up as headless and my access is with Windows 10 using PuTTY, WinSCP and TightVNC Viewer.

I run the server by opening a terminal window and the following command:

sudo python app1c.py 

This sets up the server and I can access my xml file quite well. However, when I turn off the Windows machine and the PuTTY session, the Flask server shuts down!

How can I set it up so that the Flask server continues even when the Windows machine is turned off?

I read in the Flask documentation:

While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well and by default serves only one request at a time.

Then they go on to give examples of how to deploy your Flask application to a WSGI server! Is this necessary given the simple application I am dealing with?

like image 400
Gary Avatar asked Apr 07 '16 02:04

Gary


3 Answers

Use:

$ sudo nohup python app1c.py > log.txt 2>&1 &

nohup allows to run command/process or shell script that can continue running in the background after you log out from a shell.

> log.txt: it forword the output to this file.

2>&1: move all the stderr to stdout.

The final & allows you to run a command/process in background on the current shell.

like image 67
Gal Mal Avatar answered Nov 09 '22 02:11

Gal Mal


Install Node package forever at here https://www.npmjs.com/package/forever
Then use

forever start -c python your_script.py

to start your script in the background. Later you can use

forever stop your_script.py

to stop the script

like image 42
Peixiang Zhong Avatar answered Nov 09 '22 02:11

Peixiang Zhong


You have multiple options:

  1. Easy: deattach the process with &, for example:

$ sudo python app1c.py &

  1. Medium: install tmux with apt-get install tmux launch tmux and start your app as before and detach with CTRL+B.

  2. Complexer: Read run your flask script with a wsgi server - uwsgi, gunicorn, nginx.

like image 8
oz123 Avatar answered Nov 09 '22 03:11

oz123