Sunday, June 7, 2015

Generating the simplest possible nginx load-balancing config

I recently had to put together a load-balancing configuration for nginx and wish that I had a shell script to generate the very simplest possible nginx setup.  I think I have it now:

:
if [ -z "$1" ]; then
echo "Usage: $0 URI HOST1 HOST2 ..."
exit 1
fi
uri="$1"
shift
hosts=$@
out=/etc/nginx/nginx.conf
if [ ! -f $out.bak ]; then
        mv $out $out.bak
fi
cat <<EOF > $out
events {
}
http {
        upstream configuration_servers {
EOF

for h in $hosts; do
        echo "                server $h:8080;"
done >> $out

cat <<EOF >> $out
        }
        server {
                listen       80;
                location $uri {
                proxy_pass http://configuration_servers$uri;
                }
        }
}
EOF

cat $out

service nginx restart

url=localhost:80$uri
if ! curl $url; then
        echo "$0: curl $url failed, exiting..." 1>&2
        exit 1
fi