Tuesday 26 March 2019

How to run python applications as system service in CentOS 7 or RHEL 7 ?

I started developing python applications from 2012. During my learning period, I was using screen in linux for running my python applications in the background. Majority of my colleagues were also following the same approach for running applications in background. The advantage of this approach was its easiness. But these screens will go away if the system gets rebooted. Also these applications will never get started on boot.

Systemd is a system and service manager for CentOS 7 and RHEL 7. This the first process that gets started after the system boots. This is compatible with the SysV init scripts used by CentOS 6 and RHEL 6.

It is very easy to run any custom application as a system service. In this way, the management will become very easy.

Suppose I have a python flask application app.py and I want to run it as a system service. I want to run this application under my unix user account amal.  

The contents of app.py is given below.




My code is located in the location /home/amal. Usually in case of any production deployment, the code will not be kept in the user home directory. This is to explain the scenario of running the application as a non root user.

The command to run my application is


python app.py 

For running in production mode with a WSGI like gunicorn, the command will be
gunicorn app:app --bind 0.0.0.0:8080 -w 2

For running this application as system service. We just need to do the following steps.

Create a file myapp.service in the location /etc/systemd/system/ The content of myapp.service is given below.


Now save the file and execute the following command. The following command will reload all the systemd configurations.
systemctl daemon-reload

Now we can start the application with the following command
systemctl start myapp

Now check the status of the application with the following command
systemctl status myapp

Also we can invoke the webservice using curl command.
curl -X GET http://localhost:8080/


No comments:

Post a Comment

How to check the memory utilization of cluster nodes in a Kubernetes Cluster ?

 The memory and CPU utilization of a Kubernetes cluster can be checked by using the following command. kubectl top nodes The above command...