Skip to content

Instantly share code, notes, and snippets.

@adrianuf22
Last active October 10, 2018 18:14
Show Gist options
  • Save adrianuf22/5d6c34fe17467d6e2646c6d805c81cd0 to your computer and use it in GitHub Desktop.
Save adrianuf22/5d6c34fe17467d6e2646c6d805c81cd0 to your computer and use it in GitHub Desktop.
Nginx Load balance + Health check
user root;
worker_processes auto;
worker_rlimit_nofile 1048576;
pid /run/nginx.pid;
events {
worker_connections 1048576;
use epoll;
multi_accept on;
}
http {
include /usr/local/nginx/conf/mime.types;
default_type application/octet-stream;
error_log /usr/local/nginx/logs/error.log debug;
error_log /dev/stdout warn;
lua_shared_dict healthcheck 1m;
upstream casts {
include upstream_servers.conf;
}
init_worker_by_lua_block {
local hc = require "resty.upstream.healthcheck"
local upstream = require "ngx.upstream";
local upstreams = upstream.get_upstreams()
local healthCheckArgs = {
shm = "healthcheck", -- defined by "lua_shared_dict"
type = "http",
interval = 5000, -- Check every 5 sec
timeout = 1000, -- 1 sec is the timeout for network operations
fall = 3, -- # of successive failures before turning a peer down
rise = 2, -- # of successive successes before turning a peer up
valid_statuses = {200, 302},
}
for ix, upstream_name in ipairs(upstreams) do
ngx.log(ngx.INFO, 'Current upstream', upstream_name)
local servers = upstream.get_servers(upstream_name)
local totalServers = table.getn(servers)
healthCheckArgs.upstream = upstream_name;
healthCheckArgs.http_req = "GET /status HTTP/1.0\r\nHost: " .. upstream_name .. "\r\n\r\n";
healthCheckArgs.concurrency = totalServers;
local ok, err = hc.spawn_checker(healthCheckArgs)
if not ok then
ngx.log(ngx.WARN, "failed to spawn health checker: ", err)
return
end
end
}
server {
location / {
proxy_pass http://shoutcast;
proxy_next_upstream error timeout http_500 http_502 http_503 http_504 http_429 http_403 http_404;
}
location /status {
access_log off;
allow 127.0.0.1;
deny all;
default_type text/plain;
content_by_lua_block {
local hc = require "resty.upstream.healthcheck"
ngx.say("Nginx Worker PID: ", ngx.worker.pid())
ngx.print(hc.status_page())
}
}
}
}
server 127.0.0.2:8004;
server 127.0.0.3:8006;
server 127.0.0.4:8005 backup;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment