Cara Setting Load Balancing dengan Nginx

Install Nginx dan PHP-FPM di Node

Install Nginx di Node1 dan Node2.
sudo apt install nginx php php-fpm -y sudo systemctl status nginx sudo systemctl status php7.2-fpm
Membuat file index.php di Node1.
sudp mkdir /var/www/defnex.com sudo echo "<h1>node1</h1>" > /var/www/defnex.com/index.php
Membuat file index.php di Node2.
sudp mkdir /var/www/defnex.com sudo echo "<h1>node2</h1>" > /var/www/defnex.com/index.php
Membuat server block di Node1 dan Node2.
sudo nano /etc/nginx/conf.d/domainmu.com.conf
File konfigurasi server block.
server { listen 80; server_name domainmu.com www.domainmu.com; root /var/www/domainmu.com/; index index.php index.html index.htm; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { try_files $fastcgi_script_name =404; include fastcgi_params; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; fastcgi_index index.php; fastcgi_param DOCUMENT_ROOT $realpath_root; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; } access_log /var/log/nginx/domainmu.com.access.log; error_log /var/log/nginx/domainmu.com.error.log warn; }
Uji dan restart Nginx.
sudo nginx -t sudo systemctl restart nginx sudo systemctl status nginx

Install dan Konfigurasi Nginx di Load Balancer

Install Nginx.
sudo apt install nginx -y sudo systemctl status nginx
Membuat server block untuk load balancing domain domainmu.com.
sudo nano /etc/nginx/conf.d/lb-domainmu.com.conf
File konfigurasi server block load balancing domain domainmu.com.
upstream backend { server 10.130.127.167; #node1 server 10.130.128.35; #node2 } server { listen 80; server_name defnex.com www.defnex.com; location / { proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_pass http://backend; } }
Pada konfigurasi upstream backend dituliskan IP address dari backend server. Secara default metode load balancing yang digunakan adalah Round Robin
Konfigurasi load balancing jika menggunakan metode Least Connections.
upstream backend { least_conn; server 10.130.127.167; #node1 server 10.130.128.35; #node2 }
Konfigurasi load balancing jika menggunakan metode IP Hash.
upstream backend { ip_hash; server 10.130.127.167; #node1 server 10.130.128.35; #node2 }
Uji dan restart Nginx.
sudo nginx -t sudo systemctl restart nginx sudo systemctl status nginx


Type above and press Enter to search.

Code Copied!