deconya
deconya

Reputation: 77

Code to enable healthcheck in node app for ALB

Im checking to enable Application Load Balancer in AWS using Node. In my EC2 instances Im using a nginx proxy to send to 3000 port and all I configure is a "/healthcheck" path to validate in nginx and node the health control. In nginx was quite easy

location /healthcheck {
return 200;

}

But for node I can't find a clean example to enable same function for 3002 port. For now Im having a timeout error.

Thanks

PD: I checked history and last answer is 3 years old creating a ping.html file How to configure AWS Elastic Load Balancer's heath check for Node.js

Upvotes: 1

Views: 4562

Answers (2)

O. Jones
O. Jones

Reputation: 108851

I've done this. In my case it was for AWS's DNS latency-based routing service, but it works the same.

I set up a /health endpoint in my nodejs program. That's pretty simple to do with express. I then put this stanza in nginx.conf.

         location /health {

              proxy_pass http://relay/health;
              proxy_http_version 1.1;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection 'upgrade';
              proxy_set_header Host $host;
              proxy_set_header        X-Real-IP       $remote_addr;
              proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
         }

All that stuff is there to persuade your nginx reverse proxy to pass along the origin host address to the nodejs server. My server's called "relay", yours is obvs something different.

My /health endpoint is set up to return 200 when all is well, and 503 ("service unavailable" a/k/a "try again later") when the particular server is overloaded or in the process of going offline. A totally dead server simply doesn't respond, which the AWS DNS service interprets correctly, as does the ALB service.

I also threw in a very small JSON object describing the server's current status, when it was built and launched, and a few other details. Nice for monitoring.

Upvotes: 1

Ashish Modi
Ashish Modi

Reputation: 7770

You basically need to expose a healtcheck endpoint. It will depend on what are you using to create a web server. options are express, http, hapijs etc. The simplest route using express could be

const express = require('express')
const app = express()
const port = 3002

app.get('/healthcheck', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

In your ALB, you can simply use http://someIp:3002/healthcheck. If it returns 200 that means your app is up else not. You need to make sure the port is also open for communication on your ec2.

Upvotes: 3

Related Questions