My nginx.conf file currently has the routes defined directly:
worker_processes auto;
events { worker_connections 1024; }
http {
upstream wordSearcherApi {
least_conn;
server api1:61370 max_fails=3 fail_timeout=30s;
server api2:61370 max_fails=3 fail_timeout=30s;
server api3:61370 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
server_name server_name 0.0.0.0;
location / {
proxy_pass http://wordSearcherApi;
}
}
}
Is there any way to create just one service in docker-compose.yml and when docker-compose up --scale api=3
, does nginx do automatic load balance?
Nginx
Dynamic upstreams are possible in Nginx (normal, sans Plus) but with tricks and limitations.
You give up on
upstream
directive and use plainproxy_pass
.It gives round robin load balancing and failover, but no extra feature of the directive like weights, failure modes, timeout, etc.
Your upstream hostname must be passed to
proxy_pass
by a variable and you must provide aresolver
.It forces Nginx to re-resolve the hostname (against Docker networks' DNS).
You lose
location
/proxy_pass
behaviour related to trailing slash.In the case of reverse-proxying to bare
/
like in the question, it does not matter. Otherwise you have to manuallyrewrite
the path (see the references below).Let's see how it works.
docker-compose.yml
nginx.conf
Then...
...produces something like the following which indicates the requests are distributed across 4
app
containers:References:
Traefik
Traefik relies on Docker API directly and may be a simpler and more configurable option. Let's see it in action.
docker-compose.yml
Then...
...also produces something the output that indicates the requests are distributed across 4
app
containers:In the Traefik UI (
http://localhost:8081/dashboard/
in the example) you can see it recognised the 4app
containers:References:
It's not possible with your current config since it's static. You have two options -
1. Use docker engine swarm mode - You can define replicas & swarm internal DNS will automatically balance the load across those replicas.
Ref - https://docs.docker.com/engine/swarm/
2. Use famous Jwilder nginx proxy - This image listens to the docker sockets, uses templates in GO to dynamically change your nginx configs when you scale your containers up or down.
Ref - https://github.com/jwilder/nginx-proxy