From fc236a5056607527ea2a4c2e57a11ae488fd1ba6 Mon Sep 17 00:00:00 2001 From: djwinter Date: Wed, 1 Feb 2017 21:36:56 +1300 Subject: [PATCH] Allow upstreams to have multiple servers for load balancing --- main.go | 11 ++++++++++- templates/nginx.tmpl | 10 ++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 189641c..e710b16 100644 --- a/main.go +++ b/main.go @@ -106,6 +106,15 @@ func runSignal() error { } func writeConfig(params []*container) error { + var containers map[string][]*container + containers = make(map[string][]*container); + // Remap the containers as a 2D array with the domain as the index + for _, v := range params { + if _, ok := containers[v.Host]; !ok { + containers[v.Host] = make([]*container, 0) + } + containers[v.Host] = append(containers[v.Host], v) + } tmpl, err := template.ParseFiles(*templateFile) if err != nil { return err @@ -115,7 +124,7 @@ func writeConfig(params []*container) error { return err } defer f.Close() - return tmpl.Execute(f, params) + return tmpl.Execute(f, containers) } func findClusterName() (*string, error) { diff --git a/templates/nginx.tmpl b/templates/nginx.tmpl index 60ad24b..dc241fd 100644 --- a/templates/nginx.tmpl +++ b/templates/nginx.tmpl @@ -9,16 +9,18 @@ server { return 503; } -{{ range $index, $value := . }} -upstream {{ $value.Host }} { +{{ range $domain, $container := . }} +upstream {{ $domain }} { + {{ range $_, $value := $container }} server {{ $value.Address }}:{{ $value.Port }}; + {{ end }} } server { - server_name {{ $value.Host }}; + server_name {{ $domain }}; listen 80; access_log /var/log/nginx/access.log vhost; location / { - proxy_pass http://{{ $value.Host }}; + proxy_pass http://{{ $domain }}; } } {{ end }}