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.
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  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
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.