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)

[bash]
#!/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
[/bash]

This script, on it’s own can be used as
[bash]
./haproxyd start
./haproxyd restart
./haproxyd stop
[/bash]

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

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

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

[bash]
sudo service haproxyd <command>
[/bash]

1 Comment

Submit a comment