Link Search Menu Expand Document

Load Balancer

For more nginx documentation, can review here

Table of contents

Create 3 servers

echo 'php server 1' > s1
echo 'php server 2' > s2
echo 'php server 3' > s3

Start 3 servers

php -S localhost:10001 s1
php -S localhost:10002 s2
php -S localhost:10003 s3

Create load-balancer config file, see sample config below

Steps to follow:

  1. adding proxy_pass http://localhost:10001/
  2. run monitor command while sleep 0.5; do curl http://localhost:8888; done

     0.5 = half second 
     run this command to check if the server is working, 
     the default is `round-robin`
  3. commend out the old proxy, see proxy_pass http://php_servers
  4. run monitor, see a nicely output each server
  5. use ^c to kill server 1, see the round-robin load balancing under the below monitor command

Load balancer options

sticky sessions

  • add: ip_hash; to http / upstream { … }
  • touch slow.php

          echo "sleepy server finally done\n";
      #sleep(20) means 20 second 
  • Using least_conn;

    allow nginx to avoid latency from slow.php, load balance to a faster responding server.

nginx as a service & updating a custom build


Sample configuration

# this is on local PC, not remote server 
events { ... }

http {
    upstream php_servers {
        # ip_hash;
        # least_conn;
        server localhost:10001;
        server localhost:10002;
        server localhost:10003;
    server {
        listen 8888;

        location / {
            # proxy_pass http://localhost:10001/';
            proxy_pass http://php_servers;
            # Above upstream, it's defined on php_servers