-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti-servers.js
More file actions
61 lines (52 loc) · 1.8 KB
/
Copy pathmulti-servers.js
File metadata and controls
61 lines (52 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// server.js
const express = require('express');
const httpProxy = require('http-proxy');
const axios = require('axios');
const app = express();
const proxy = httpProxy.createProxyServer({});
// Backends: must match ports from backend-cluster.js
const servers = [
{ url: 'http://localhost:5001', alive: true },
{ url: 'http://localhost:5002', alive: true },
{ url: 'http://localhost:5003', alive: true },
{ url: 'http://localhost:5004', alive: true },
// Add more servers as needed
];
let current = -1; // start at -1 so first request -> index 0
function getNextServer() {
const aliveServers = servers.filter(s => s.alive);
if (!aliveServers.length) return null;
current = (current + 1) % aliveServers.length;
return aliveServers[current];
}
// proxy incoming requests
app.use((req, res) => {
const target = getNextServer();
if (!target) {
return res.status(502).send('No backend servers are available.');
}
console.log(`→ Forwarding ${req.method} ${req.url} to ${target.url}`);
proxy.web(req, res, { target: target.url }, (err) => {
console.error(`Proxy error to ${target.url}:`, err.message);
res.status(500).send('Proxy Error');
});
});
// health checks: ping /health on each backend every 5s
async function checkServers() {
await Promise.all(
servers.map(async (server) => {
try {
await axios.get(server.url + '/health', { timeout: 1500 });
if (!server.alive) console.log(`[HEALTH] ${server.url} is back UP`);
server.alive = true;
} catch {
if (server.alive) console.log(`[HEALTH] ${server.url} is DOWN`);
server.alive = false;
}
})
);
}
setInterval(checkServers, 5000);
checkServers(); // do an initial check immediately
const PORT = 3000;
app.listen(PORT, () => console.log(`Reverse Proxy listening on port ${PORT}`));