Running a Python (or almost anything) as a service with automatic restart via Upstart

Post to Twitter

Pretty often I run into a situation where I’d like a Linux application I’ve created to run as a service. Basically, run my Python, Go (GoLang), Ruby, etc. application on start-up and respawn it if it gets any kind of termination/kill signal. Today I’ll show you how to do this with a simple Python Tornado application.


Upstart is available for basically any Linux distro. That being said I’m going to be doing this on Ubuntu 12.04 LTS.

For the example project I’m going to simply borrow the server code (currently) on the Tornado homepage.

Create a file called myservice.py and save it to a location like /home/USERNAME/myservice/myservice.py

#!/usr/bin/python

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8080)
    tornado.ioloop.IOLoop.instance().start()

Open up the Terminal program and go into the myservice.py folder. Make sure to set this file as executable:

$ chmod +x myservice.py

Make sure Tornado is installed:

$ pip install tornado

If you get an error that pip is not available then install it first:

$ sudo apt-get install python-pip

Now create a file called myservice.conf and add the following contents into it:

description "My Service"
author "YOUR NAME HERE"
 
start on (local-filesystems and net-device-up)
stop on runlevel [06]
 
respawn
exec /home/chadlung/myservice/myservice.py

Copy the file to /etc/init/ (adjust as needed if you not using Ubuntu)

$ cp /home/USERNAME/myservice/myservice.conf /etc/init/myservice.conf

You should be able to start your service now:

$ sudo service myservice start

Test it out in a web browser: http://localhost:8888

You can also stop and the service as needed:

$ sudo service myservice stop

If the service is running, try killing it and you’ll see it gets restarted automatically (it will also start when you re-boot).

$ sudo kill <INSERT PID HERE>

Obviously you’ll want to have your application in the appropriate folder when running in production but this demonstrates the basics needed to get it working. Adjust as desired and check out the excellent docs here.

Post to Twitter

This entry was posted in Open Source, Python, Tornado, Ubuntu. Bookmark the permalink.

One Response to Running a Python (or almost anything) as a service with automatic restart via Upstart

  1. Jonathan Harford says:

    Thanks very much! This is exactly what I needed to solve this issue I had with Fabric.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>