Starting on system startup and respawning apps with upstart in ubuntu

Configuring

Following is an example config file for starting app on system startup and auto-respawning.
File name should be put in /etc/init, its name should end with .conf

The name of the task is derived from file name. For file name taskName.conf, the task is called taskName.

start on runlevel [2345]

#!upstart
description "your app description"

# Start a job as username, a member of usergroup
setuid username
setgid usergroup

# set required environments (what you normally do with export VARIABLE=VALUE)
env ENV_TO_SET = environment\ value

# run the app
exec /home/myuser/bin/myapp

# Restart the process if it dies with a signal
# or exit code not given by the 'normal exit' stanza.
respawn

# Give up if restart occurs 10 times in 90 seconds.
respawn limit 10 90

Running

To start a task run:

$ sudo start taskName

And to stop it:

$ sudo stop taskName

More info: http://upstart.ubuntu.com/cookbook/

Notes

When you get some strange errors reading files, you might need to add an env which defines locale, e.g.:

env LC_ALL=pl_PL.UTF-8

For running java apps, remember to specify JAVA_HOME

setting up iptables to forward 80 (http) and 443 (https) to other ports

If you want to serve http content from application run by a non-root user, you can set up iptables to forward http and https ports to “user space ports”.

Setting up

Assuming your app uses port 8080 for http and 8081 for https, configure iptables as follows:

$ sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
$ sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8081

Saving and restoring

Test the configuration and if it works save it, e.g. with:

sudo iptables-save > /etc/iptables/rules

Now you have to add reading iptables configuration on system startup.
If your network is configured manually you can add iptables-restore < /etc/iptables/rules to your /etc/network/interfaces:

auto eth0
iface eth0 inet dhcp
        pre-up iptables-restore < /etc/iptables/rules

If your /etc/network/interfaces is generated automatically, you can create a new file in /etc/network/if-pre-up.d/ with following content:

#!/bin/bash

iptables-restore < /etc/iptables/rules
exit 0