Load Balancing Tomcat Menggunakan Nginx

Load Balancing Tomcat Menggunakan Nginx

Apa itu load balancing? Mengutip dari situs nginx: Load balancing refers to efficiently distributing incoming network traffic across a group of backend servers, also known as a server farm or server pool. Selengkapnya klik disini

Berikut ini adalah contoh load balancing aplikasi tomcat: Skenario:

  • ada dua buah server dengan tomcat berjalan di dalamnya.
  • masing-masing tomcat berjalan di port 8080.
  • setiap akses ke contoh.com akan di proxy ke upstream backend.

Berikut ini adalah konfigurasi nginxnya:

###
# Desc: Load balancing aplikasi servlet tomcat, menggunakan nginx
# Author: Sumarsono
# Create date: 2019-01-08
# Tested: Yes
##

proxy_cache_path /tmp/NGINX_cache/ keys_zone=backcache:10m;

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

upstream tomcat {
    # Use IP Hash for session persistence
    ip_hash;

    # List of Tomcat application servers
    #server 10.100.100.11:8080;
    #server 10.100.100.12:8080;
    
    #server+app tomcat 1
    server 14.252.14.28:8080;
    
    #server+app tomcat 2
    server 14.252.14.20:8080;
}

server {
    listen 80;
    server_name contoh.com;

    # Load balance requests for / across Tomcat application servers
    location / {
        proxy_pass http://tomcat;
        proxy_cache backcache;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # WebSocket configuration
    location /wstunnel/ {
        proxy_pass https://tomcat;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}