Skip to content

Instantly share code, notes, and snippets.

@CaporalDead
Last active November 3, 2016 14:21
Show Gist options
  • Save CaporalDead/c5389e0159c7818d3aa6 to your computer and use it in GitHub Desktop.
Save CaporalDead/c5389e0159c7818d3aa6 to your computer and use it in GitHub Desktop.
A script to auto update your nginx proxy for your docker containers
#!/bin/sh
MAPPING_FILE=$1
CONTAINERS=($(docker ps | awk 'NR>1' | perl -ne '@cols = split /\s{2,}/, $_; printf "%30s %20s %20s\n", $cols[6], $cols[0]' | awk '{print $1":"$2}'))
readarray DOMAINS < $MAPPING_FILE
NGINX_CONF_FILE=/etc/nginx/sites-enabled/auto-update
function getIPByName {
local NAME=$1
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $NAME
}
function getNginxConf {
local DOMAIN=$1
local IP=$2
local PORT_HOST=$3
local PORT_CONTAINER=$4
local IP_HOST=$5
local IP_PORT=""
if [ -n "$IP_HOST" ]; then
IP_PORT="$IP_HOST:$PORT_HOST"
else
IP_PORT="$PORT_HOST"
fi
cat <<EOF
server {
listen $IP_PORT;
server_name $DOMAIN;
location / {
proxy_pass http://$IP:$PORT_CONTAINER;
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-Server \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
}
EOF
}
function eraseAutoUpdateConf {
rm -rf $NGINX_CONF_FILE
}
/etc/init.d/nginx stop
eraseAutoUpdateConf
for mapping in "${DOMAINS[@]}"
do
NAME=$(echo $mapping | awk -F ':' '{print $1}')
DOMAIN=$(echo $mapping | awk -F ':' '{print $2}')
PORT_HOST=$(echo $mapping | awk -F ':' '{print $3}')
PORT_CONTAINER=$(echo $mapping | awk -F ':' '{print $4}')
IP_HOST=$(echo $mapping | awk -F ':' '{print $5}')
IP=$(getIPByName $NAME)
CONF=$(getNginxConf $DOMAIN $IP $PORT_HOST $PORT_CONTAINER $IP_HOST)
echo $CONF >> $NGINX_CONF_FILE
done
/etc/init.d/nginx start
@CaporalDead
Copy link
Author

eg : Given you have a mapping file :

/home/user/mapping-nginx :

laboard:laboard.domain.tld:80:80:1.2.3.4
gitlab:gitlab.domain.tld:80:80:2.3.4.5
gitlab-ci:gitlab-ci.domain.tld:80:80:1.2.3.4

Retrieve the script :

cd /home/user wget -O update-nginx.sh https://gist.githubusercontent.com/CaporalDead/c5389e0159c7818d3aa6/raw/b4b1f337161f006f1f2db1eff439ebcb9019938b/update-nginx chmod +x update-nginx.sh

Execute :

./update-nginx.sh /home/user/mapping-nginx

You can also put the script in /usr/bin. You need to have privileges to execute this script, it depends on your configuration (using sudo, etc...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment