Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.