How to run Flask Server in the background

Gary picture Gary · Apr 7, 2016 · Viewed 35.5k times · Source

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?

Answer

Gal Mal picture Gal Mal · May 22, 2017

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.