I just finished my app and would like to deploy it. But how to run my app as a service/deamon?
A google search showed some different approches using some python libraries, twisted and Can I run a Python script as a service?. But can't figure out how to do it.
Any one done this? Is there a best-practice approach?
..fredrik
As you want your application to run standalone (if i understood correctly), you could handle this like with any other (non-web) application.
If you just want your program to run in the background, you could read this receipe that explains how to create a daemon application and has a nice discussion about this topic (in the comments).
On the other hand, if you want to make a "system daemon" with your app (which starts at every system's startup), i'd go with a shell script. To see how to create startup scripts for your system, you could get inspiration from the other startup scripts on your machine. A solution would be to run your program in the background with python my_app.py &
(from the startup script), and then use the $!
variable to get the process' pid and store it to a file, this way you would also be able to stop your process by reading the "pid file" and use the kill
command (sending a SIGINT
to your process will provoke a KeyboardInterrupt
exception to be raised in your application).
EDIT:
In your question comments, you say using python main.py &
would be unsafe as the application wouldn't restart if it failed/crashed, but that's the same with any other daemon on your system (for example, if Apache crashed, it would'nt restart by itself). If you want to restart your application if it crashes, you would have to write a 2nd daemon, that would check at regular intervals if your application is still running, and restart it if needed.
About the logging thing, you can either make your application output to stdout/stderr
and redirect it from the startup script (python main.py &> /path/to/app.log &
) or handle logging from your application, using the logging
module.
Alternatively, you can easily run and control the deamonized process with supervisord and log its stdout/stderr output too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With