Translate

Have the latest HAProxy as a Ubuntu Service

So you need to use HAProxy and you love the convenience of binary packages on repos, but when you install the version HAProxy available in the repos you realize that it is way too old for what you need.

Then you download the latest HAProxy, compile it, configure it, but it’s a bit of a pain in the ass to not have the convenience of having haproxy be automatically restarted as a service like those available on /etc/init.d

This post teaches you how to have haproxy as a Ubuntu/Debian service.

First copy or symlink this script to your /etc/init.d/ folder (you’ll need root permissions to do this)

#!/usr/bin/env bash
# haproxyd
# Script to start|stop|restart haproxy from /etc/init.d/
# By Gubatron.

HAPROXY_PATH=/path/to/haproxy-X.Y.Z
HAPROXY_DAEMON=$HAPROXY_PATH/haproxy

test -x $HAPROXY_DAEMON || exit 0

set -e

function getHaproxyPID() {
  PID=`ps aux | grep 'haproxy -f' | grep -v "grep" | awk '{ print $2 }'`
}

case $1 in
  start)
        echo "Starting haproxy..."
        $HAPROXY_DAEMON -f $HAPROXY_PATH/haproxy.cfg
        ;;
  restart)
        echo "Hot restart of haproxy"
        getHaproxyPID
        COMMAND="$HAPROXY_DAEMON -f $HAPROXY_PATH/haproxy.cfg -sf $PID"
        echo $COMMAND
        `$COMMAND`
        ;;
  stop)
        echo "Stopping haproxy"
        getHaproxyPID
        COMMAND="kill -9 $PID"
        echo $COMMAND
        `$COMMAND`
        ;;
  *)
        echo "Usage: haproxyd {start|restart|stop}" >&2
        exit 1
        ;;
esac

exit 0

This script, on it’s own can be used as

./haproxyd start
./haproxyd restart
./haproxyd stop

But you want this script registered on all the right runlevels of the operating system.

With Ubuntu/Debian there’s a utility called update-rc.d to register /etc/init.d/ scripts very easily.

Once the script above is available on /etc/init.d do the following

cd /etc/init.d
sudo update-rc.d haproxyd defaults

The script should now be registered on all the right runlevels and you should be able to invoke it as a service like

sudo service haproxyd <command>
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

One Response to “Have the latest HAProxy as a Ubuntu Service”

  1. Wes Says:

    A different version that allows status checks: https://gist.github.com/1509227

Leave a Reply