Skip to content

Instantly share code, notes, and snippets.

@skirsten
Created June 12, 2019 12:22
Show Gist options
  • Save skirsten/032e10049a5de324e740c9456cf8c6d7 to your computer and use it in GitHub Desktop.
Save skirsten/032e10049a5de324e740c9456cf8c6d7 to your computer and use it in GitHub Desktop.
Super simple docker-compose automatic tcp load balancer using nginx and docker-gen
version: "3"
services:
whoami: # the service(s) you want to load balance
image: jwilder/whoami # this is an example placeholder (keep in mind that browsers keep connections open)
labels:
publish: "8000" # which port of this server to publish to the load balancer
nginx:
image: nginx
container_name: lb_nginx_frontend
volumes:
- nginx-config:/etc/nginx:ro
ports:
- 80:80 # nginx listens on port 80 by default -- can be changed in nginx.tmpl
docker-gen:
image: jwilder/docker-gen
volumes:
- /var/run/docker.sock:/tmp/docker.sock:ro
- nginx-config:/etc/nginx
- ./nginx.tmpl:/etc/docker-gen/templates/nginx.tmpl
command: -notify-sighup lb_nginx_frontend -watch /etc/docker-gen/templates/nginx.tmpl /etc/nginx/nginx.conf
volumes:
nginx-config:
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
{{ $backends := whereLabelExists $ "publish" }}
{{ $backendCount := len $backends }}
stream {
{{ if ne $backendCount 0 }}
upstream backend {
{{ range $index, $backend := $backends }}
# {{ $backend.Name }}
server {{ $backend.Name }}:{{ $backend.Labels.publish }};
{{ end }}
}
{{ end }}
{{ if ne $backendCount 0 }}
server {
listen 80;
proxy_pass backend;
}
{{ end }}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment