Last active
February 3, 2023 00:18
-
-
Save ryan-wendel/c09d24d9d25d5ca4ba8d605169e5ee86 to your computer and use it in GitHub Desktop.
A quick & dirty script to spin up an nginx container that will load balance requests to a Kubernetes cluster
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
print_help() { | |
echo | |
echo "Usage: $(basename $0) -p port [-p port] -s server [-s server]" | |
echo | |
} | |
TMP_DIR="/tmp/nginx_conf_$$" | |
while getopts "p:s:" OPT; do | |
case "${OPT}" in | |
p) PORTS="${OPTARG},${PORTS}";; | |
s) SERVERS="${OPTARG},${SERVERS}";; | |
h) print_help; exit 1;; | |
:) print_help; exit 1;; | |
esac | |
done | |
# bounce if wrong number of args | |
[[ ${OPTIND} -eq 1 ]] && print_help && exit 1 | |
shift "$((OPTIND - 1))" | |
# make a temp dir for nginx conf | |
mkdir -p ${TMP_DIR}/conf | |
# dynamically build our nginx conf file | |
cat << EOF > ${TMP_DIR}/conf/nginx.conf | |
events {} | |
stream { | |
log_format basic '\$remote_addr [\$time_local] ' | |
'\$protocol \$status \$bytes_sent \$bytes_received ' | |
'\$session_time'; | |
access_log /dev/stdout basic; | |
EOF | |
# build our upstream apps | |
APP_NUMBER="1" | |
while read PORT; do | |
cat << EOF >> ${TMP_DIR}/conf/nginx.conf | |
upstream app${APP_NUMBER} { | |
EOF | |
while read SERVER; do | |
cat << EOF >> ${TMP_DIR}/conf/nginx.conf | |
server ${SERVER}:${PORT}; | |
EOF | |
done < <(echo ${SERVERS} | sed 's/,$//' | tr ',' '\n' | sort -u) | |
cat << EOF >> ${TMP_DIR}/conf/nginx.conf | |
} | |
EOF | |
let APP_NUMBER+=1 | |
done < <(echo ${PORTS} | sed 's/,$//' | tr ',' '\n' | sort -u) | |
# reset the app number | |
APP_NUMBER="1" | |
# build our servers | |
while read PORT; do | |
cat << EOF >> ${TMP_DIR}/conf/nginx.conf | |
server { | |
listen ${PORT}; | |
proxy_pass app${APP_NUMBER}; | |
} | |
EOF | |
let APP_NUMBER+=1 | |
done < <(echo ${PORTS} | sed 's/,$//' | tr ',' '\n' | sort -u) | |
# close out file | |
cat << EOF >> ${TMP_DIR}/conf/nginx.conf | |
} | |
EOF | |
# create our port flags for docker command | |
PORT_ARGS="" | |
while read PORT; do | |
[[ -n ${PORT_ARGS} ]] && PORT_ARGS="-p ${PORT}:${PORT} ${PORT_ARGS}" || PORT_ARGS="-p ${PORT}:${PORT}" | |
done < <(echo ${PORTS} | sed 's/,$//' | tr ',' '\n' | sort -u) | |
docker run ${PORT_ARGS} -v ${TMP_DIR}/conf:/tmp/conf nginx nginx -c /tmp/conf/nginx.conf -g "daemon off;" | |
rm -Rf ${TMP_DIR} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment