How to prepare any program for running in a background as a service on CentOS

In this post we will discuss how to use supervisor system built with python.

At first we need to install supervisor system, it could be done via pip, check for this – http://supervisord.org/installing.html or via package manager yum.

For this we must be sure to have an EPEL repository, update system with latest packages:

sudo yum install epel-release
sudo yum update

and install supervisor itself:

sudo yum install supervisor

Then start daemon:

sudo systemctl start supervisord

and finally, enable it:

sudo systemctl enable supervisord

Now check if everything is ok, supervisor daemon is enabled, active and running:

sudo systemctl status supervisord

Now we need to prepare supervisor configuration file to run our program, by preparing related program sections with according environment variables.

The configuration file on CentOS might be found at location:

/etc/supervisord.conf

At first we must create [program:my-program-name] section and add at least command attribute with value:

[program:my-program-name]
command=/full/path/to/my/program.py some arguments

One main argument is numprocs – this defines how many instances should be run. If this is a case, then process_name also must be defined and it must include the expression %(process_num)s:

numprocs=2
process_name=%(program_name)s_%(process_num)s

Some other useful options are:

autostart=true
autorestart=true
user=user
redirect_stderr=true
stdout_logfile=/full/path/to/my/supervisor.log

After configuration, it’s time to run our program. As new program added / the configuration file changed – supervisor daemon’s already loaded config file must be reloaded with the next command:

supervisorctl update

In this case configuration file will be reloaded, new program will be started and next message will be displayed:

my-program-name: added process group

By the way, you can check all running programs with the next code:

supervisorctl status

where you should see our newly added program:

my-program-name:my-program-name_0 RUNNING pid 7577, uptime 0:00:07

More about configuration, check: http://supervisord.org/configuration.html#program-x-section-settings

Full documentation: http://supervisord.org/index.html

Leave a Reply

Your email address will not be published. Required fields are marked *