user nginx;
worker_processes 1;

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    {% for service in service_groups.get('http', []) %}
    upstream {{ service.name }} {
        least_conn;
        {% for instance in service.instances %}
        server {{ instance.Address }}:{{ instance.ServicePort }} max_fails=3 fail_timeout=60 weight=1;{% endfor %}
    }{% endfor %}

    server {
        listen 80;

        location / {
            root html;
            index index.html;
        }

        {% for service in service_groups.get('http', []) %}
        location /{{ service.name }} {
            proxy_pass http://{{ service.name }};
        }{% endfor %}
    }
}

stream {
    {% for port, service in service_groups.get('stream', {}).items() %}
    upstream {{ service.name }} {
        least_conn;
        {% for instance in service.instances %}
        server {{ instance.Address }}:{{ instance.ServicePort }} max_fails=3 fail_timeout=60 weight=1;{% endfor %}
    }

    server {
        listen {{ port }}{% if 'udp' in service.tags %} udp{% endif %};
        proxy_pass {{ service.name }};
    }{% endfor %}
}
