Search code examples
apinginxparse-server

nginx load balancing - do I have to have multiple copies of my API?


I want to load balance my Parse API using NGINX

My API runs currently on nginx on one server, if I want to load balance it, do I have to host my API on every host ?

I want it to look like this

----------                             /----- [ api-0.myhost.com ]
| client | --------> [ api.myhost.com ] ----- [ api-1.myhost.com ]
----------                             \----- [ api-2.myhost.com ]

In this case do I have to install nginx and deploy my API to very api-X.myhost.com ?

Or I just deploy my API on api.myhost.com and on the api-X.myhost.com I just install nginx ?


Solution

  • You just install nginx on api.host.com, then configure nginx for load balancing as below:

    upstream api-app {
                  least_conn;
                  server api-0.myhost.com:port weight=1 max_fails=1;
                  server api-2.myhost.com:port weight=1 max_fails=1;
                  server api-3.myhost.com:port weight=1 max_fails=1;   
    
            }
    
            server {
                  listen 80;
                  listen  443 ssl;
                  server_name api.myhost.com;
    
    
    
                  ssl_certificate /etc/ssl/certs/api_ssl-bundle.crt;
                  ssl_certificate_key /etc/ssl/private/api_com.key;
    
                  client_max_body_size 2000M;
                  large_client_header_buffers 32 128k;
                  location / {
                   proxy_set_header X-Real-IP $remote_addr;
                   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    
                    proxy_buffers 64 128k;
                    proxy_buffer_size 256k;
                    proxy_pass http://api-app;
                    proxy_connect_timeout   1200;
                    proxy_send_timeout      1200;
                    proxy_read_timeout      1200;
                    proxy_http_version 1.1;
                    proxy_set_header Upgrade $http_upgrade;
                    proxy_set_header Connection "";
                    proxy_set_header Host $host;
                    proxy_cache_bypass $http_upgrade;
                  }
            }
    

    With port is a port which your api-app listen on its host.