When you write any python code (Especially Web-Framework be it in Flask & Django) and run locally on Terminal/Command-line - We can't use particular terminal window.
if we want to run any other commands, we have to open other terminal; like below.
Let's consider very simple code written in Flask -
Create any directory and inside that directory create app.py file
Write below code in app.py
Run app.py using python3 app.py (I have 2 version of python, thus I use python3)
So, we could see - Now we can't do anything on same Terminal. If we have to run any command - we've to open new window OR terminate (Ctrl + C) the current session. if we terminate - Then our server will also get stop.
We have different ways to RUN Python code in background
1) using nohup
Nohup is short for “No Hangups.”
Run the app.py using below command (Do Not forget to add '&' at the end)
Now our application will starts in backend and it free the terminal. We can see the process using command ps a
ps ==> list process a ==>all users
We could see our application is running on PID 146821
we can kill our process using KILL pid_number i.e. KILL 146821
nohup command writes the output in nohup.out (by default). Now,we could see one extra file (nohup.out) in our directory
Whatever comes on terminal - now will write to nohup.out
if you want output/logs in some other file then we need to explicitly mention the same in command
nohup python3 app.py > output.log & [ Don't forget to add '&' at the end of command]
Now, instead of nohup.out, logs will be written in output.log
Our app will be UP (Until we manually KILL the PID or we shutdown our machine (here it's machine i.e. our computer not terminal)
2) using supervisord
Supervisor is a client/server system that allows its users to monitor and control a number of processes on UNIX-like operating systems.
supervisord = is a deamon, in linux generally if process ended with letter 'd' i.e. is a daemon (a background process)
we need to create one configuration file in path
/etc/supervisor/conf.d
- cd /etc/supervisor/conf.d
- touch app.conf
- nano app.conf
Now write below code in app.conf
The last line is path, where we have app.py
Now time to reload the configuration and update it. Run below 2 commands.
supervisorctl – Manage the group of programs running via supervisord.
we could see our app.py process has been recognized.
That's it. Nothing else we need to do, Just browse localhost:5000 or whatever the port you have for your application.
the advantage of supervisord is - when your machine rebooted, application will automatically get started.