Use HAProxy with Environment Variables as Service – Debian Jessie

debiandebian-jessieenvironment-variableshaproxy

I am new to Linux and are trying to configure HAProxy with environment variables. I am running Debian 8 (Jessie) and HAProxy 1.5.8 that I installed using apt-get as per https://haproxy.debian.net/#?distribution=Debian&release=jessie&version=1.5

Without environment variables the configuration works excellent.

I followed the instructions from this answer (setting the environment variable from /etc/init.d/haproxy)to get environment variables working but still got the 503 – Service Unavailable response.

I then looked through /etc/init.d/haproxy and thought that these two lines maybe changed the scope of what variables were available

[ -f /etc/default/rcS ] && . /etc/default/rcS
. /lib/lsb/init-functions

so I commented them out.

I can then start HAProxy using sudo /etc/init.d/haproxy startand my configuration works as I expect but when I try to run sudo service haproxy start I still get the 503 – Service Unavailable.

It seems to me like this question has the answer I'm looking for but I have not been able to translate the answers from there to my domain.

This is the part of the haproxy.cfg file where I'm using environment variables:

backend backend1
    server EnvVar ${SERVER_IP}:86 maxconn 512

I have also looked through some other questions here without finding a solution to my problem.

How do I set an environment variable so that it can be read by haproxy when haproxy is run as a service?

Best Answer

I finally figured it out.

In /lib/systemd/system/haproxy.service there is a line like this

EnvironmentFile=-/etc/default/haproxy

I looked in /etc/default/haproxy and this is what it looks like:

# Defaults file for HAProxy
#
# This is sourced by both, the initscript and the systemd unit file, so do not
# treat it as a shell script fragment.

# Change the config file location if needed
#CONFIG="/etc/haproxy/haproxy.cfg"

# Add extra flags here, see haproxy(1) for a few options
#EXTRAOPTS="-de -m 16"

I added my environment variable there and reverted the rest of my changes and it works both when running as a service and when running it directly using /etc/init.d/haproxy.

This is the line I added:

SERVER_IP=165.88.76.44