Mar 6, 2014

Run Python as service

Updated: in 2016+, it's the best to use Systemd


Using Python event-driven such as Tornado, we can develop a great system as an alternative to NodeJS technology. However, keep it running as a system service is not built-in. We have to managed ourself to do this. Luckily there is Supervisord http://supervisord.org , written in Python, and greatly get our service in Python up. It can serve not only Python, but almost every program. The installation is trivial in Ubuntu with apt-get install supervisor. Other distro can use pip install supervisor. Below is the case of Ubuntu server installation. We need to create a conf file at /etc/supervisor/conf.d/, as example a-svc.conf (noted the file extension)
[program:a-svc]
process_name=a-svc
user=www-data
dicretory=/srv/svc/
command=/usr/bin/python3 -u -m tornado.autoreload /srv/svc/service.py
# Two setting below is interesting
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/var/log/supervisor/svc.log
Then bring all up running with sudo service supervisor restart Assume our service running at 9876 We can test using curl http://127.0.0.1:9876/a-query To public this service, we can add some kind of config in Nginx:
server {
    # For public access
    location /api/ {
     rewrite ^/api/(.*)$ /$1 break;
     proxy_pass http://127.0.0.1:9876;
 }
}
We have it done nicely!


No comments:

Post a Comment

New comment