Search code examples
dockernginxdocker-swarm

Docker swarm reverse proxy+load balancing with Nginx


I have a docker compose file with 2 services: joomla and phpmyadmin.

I need a reverse proxy which behaves like below:

path: / --> joomla service

path: /managedb --> phpmyadmin service

server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://joomla;
    }
    location /managedb {
        proxy_pass http://phpmyadmin;
    }
}

Everthing works well, however I'd need to add load balancing to balance work between my 3 machines in docker swarm.

They all are VM on the same LAN with static IP 192.168.75.11/12/13.

The Nginx way to add load balancing should be the follow:

upstream joomla_app {
        server 192.168.75.11;
        server 192.168.75.12;
        server 192.168.75.13;
}
upstream phpmyadmin_app {
        server 192.168.75.11;    
        server 192.168.75.12;
        server 192.168.75.13;
}
server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://joomla_app;
    }
    location /managedb {
        proxy_pass http://phpmyadmin_app;
    }
}

However, since the only exposed port is the Ngxinx 80 one because i need it as reverse proxy too, the code above is obviously not working.

So how can I add the load balancing in this scenario?

Thank you in advance!


Solution

  • In docker swarm, you don't need own load balancer, it has a built in one. Simply scale your services and that's all. Swarm name resolver will resolve joomla and phpmyadmin either to a virtual ip that will be a swarm lb for that service or if you configure service to work in dnsrr mode, will use a dns round-robin method when resolving servicename-hostname to container ip.

    However, if you want to distribute services across nodes in swarm, that's a different thing. In this case, you can set placement restrictions for each service or set them to be "global" instead replicated - see https://docs.docker.com/engine/swarm/services/#control-service-placement