Skip to content

Instantly share code, notes, and snippets.

@cmoore4
Created October 26, 2015 15:40
Show Gist options
  • Save cmoore4/4659db35ec9432a70bca to your computer and use it in GitHub Desktop.
Save cmoore4/4659db35ec9432a70bca to your computer and use it in GitHub Desktop.
Docker-Compose Auto-Scale with Nginx Upstreams
nginx:
image: myclient/nginx
environment:
- HOSTHOST=UBUNTU
- PROXY_PORT=8069
links:
- myservice:myservice
ports:
- "80:80"
- "443:443"
daemon off;
worker_processes 4;
events{
worker_connections 4096;
}
http{
upstream myservice {
## This is the important part, and the following line will be replaced with all of the ip:port ##
## combinations from the instances of docker-compose scaling ##
--PROXY_UPSTREAM_REPLACEMENTS--
}
server {
listen 443 default;
server_name myservice.io www.myservice.io;
root /usr/share/nginx/html;
index index.html index.htm;
location / {
proxy_pass http://myservice;
# force timeouts if the backend dies
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_redirect off;
# set headers
proxy_set_header Host $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 https;
# This adds the docker internal IP to the response
add_header X-Backend-Server $upstream_addr;
}
}
}
#!/bin/bash
NEWLINE=$'\n'
ALLSERVERS=''
# This line extracts all of the environment vars that contain the port being proxied and the host's host name
SERVERS=$( env | grep "${HOSTHOST}_.*${PROXY_PORT}_TCP_ADDR" | sed 's/_PORT.*/ /g' - )
# We'll loop through all the deteced servers that match the pattern, and insert thier values: IP and Port number
for server in $SERVERS
do
servervar="${server}_PORT_${PROXY_PORT}_TCP_ADDR"
serverport="${server}_PORT_${PROXY_PORT}_TCP_PORT"
ALLSERVERS="$ALLSERVERS \n server ${!servervar}:${!serverport};"
done
# Echo out the results to the Docker log
echo "Adding Linked Contianers to NGINX conf:$NEWLINE $ALLSERVERS"
# and replace the actual entry in the nginx.conf file
sed "s/--PROXY_UPSTREAM_REPLACEMENTS--/$ALLSERVERS/g" /etc/nginx/nginx.conf.vars > /etc/nginx/nginx.conf
# Finally, start nginx
nginx
@hyzhak
Copy link

hyzhak commented Mar 21, 2016

environment vars will obsolete soon in docker, is there any other solutions?
https://gist.github.com/cmoore4/4659db35ec9432a70bca#file-run-sh-L7

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