Nodejs Micro-service Health Screening Program

Source: Internet
Author: User

1. Preface

For the current cloud platform solution, because of network, host status and many other factors, a single host of services on the chance of a significant increase in problems. This requires that we be able to monitor the health status of each host and every micro-service instance. so for Nodejs related projects need to do related micro-service health Check interface.

without altering the original Express framework, I found a sample of the corresponding health check on the Official Express website and made a demo for everyone's reference.

(Link https://expressjs.com/en/advanced/healthcheck-graceful-shutdown.html)

2.Solution ImplementationDemo

I am the agent to do the demo, the following is my modified app. js Code: The Red code for the part I added. Provide a corresponding health check port for the container.

varExpress = require (' Express ');varPath = require (' path ');varFavicon = require (' Serve-favicon '));varLogger = require (' Morgan ');varCookieparser = require (' Cookie-parser '));varBodyparser = require (' Body-parser '));varSession = require (' express-session ');varRedisstore = require (' Connect-redis ')) (session);varConfig = require ('./config/config ')). getinstance (). config;varLogg =Config.logger;varmoment = require (' moment '));varComm = require ('./middlewares/comm '));varRoutes = require ('./routes/index ')); varApp =Express (); App.set (' env ', config.debug? ' Development ': ' Production '); App.set (' Port ', Process.env.PORT | |config.port); App.set (' Trust proxy ', config.proxy);//specify subnets and IP addressesApp.set (' Views ', Path.join (__dirname, ' views '))); App.set (' View engine ', ' Ejs '); App.use (Favicon (Path.join (__dirname,' Public ', ' Favicon.ico ')) ; App.use (Logger (' Dev ') ; App.use (Bodyparser.json ()); App.use (bodyparser.urlencoded ({extended:false}); App.use (Cookieparser ()); App.use (express.static (Path.join,' Public ')));//Session Redis StorageConst Store=NewRedisstore ({host:config.redis.host, Port:config.redis.port, PASS:CONFIG.REDIS.PASSWD,});//Set SessionApp.use (Session ({Store:store, Name:' Ghjhgz ', Secret:' DFGDFGFDGDFGDFGDERTE435SD ', Resave:true, rolling:true, saveuninitialized:false, Cookie: {domain:config.domain}});//add a required variable to a templateApp.use (function(req, res, next) {Res.locals.user= ' '; Next ();}); Routes (app);//Error HandlerApp.use (function(Err, req, res, next) {//set locals, only providing error in developmentLogg.error (ERR); Res.locals.message=Err.message; Res.locals.error= Req.app.get (' env ') = = = ' Development '?err: {}; //render the error pageRes.status (Err.status|| 500); if(config.debug) {Res.render (' Error '); }Else{Res.render (' 404 '); } }); /*Istanbul Ignore Next*/if(!module.parent) {App.listen (Config.port,function() {Console.log (' Listening on port: ' +config.port); });} Module.exports= app;
View Code

1Const HTTP = require (' http ');2 3const Terminus = require (' @godaddy/terminus ');4 5Const SERVER =Http.createserver (app);6 7  functiononsignal () {8 9Console.log (' Server is starting cleanup ');Ten  One   //start cleanup of resource, like databases or file descriptors A  - }  -  theAsyncfunctionOnhealthcheck () { -  -   //checks if the system is healthy, like the DB connection is live -  +   //resolves, if health, rejects if not -  +Console.log (' Healthcheck is starting '); A  at } - Terminus (server, { -  -Signal: ' SIGINT ', -  - healthchecks: { in  -'/healthcheck ': Onhealthcheck, to  +   }, -  the onsignal *  $ }); Panax Notoginseng  -Server.listen (3000);
View Code

at present, only need to modify the App.js,onhealthcheck function interface for the health check interface, the subsequent can provide check the corresponding system health, such as database or redis link state.

2.1 Dependent library terminus

NPM i @godaddy/terminus–save installation dependencies

Terminus is an open source project that adds health checks and normal shutdowns to your application, eliminating the need to write boilerplate code. You only need to provide cleanup logic for graceful shutdown and the health check logic for health checks, while the endpoint handles the rest.

2.2Limited inWindowsSupport

due to the inherent platform limitations,Terminus has limited support for Windows . You can expect SIGINT to work, and to Sigbreak to some extent SIGHUP. However,SIGTERM never works on Windows because the Avira process in Task Manager is unconditional, that is, the application cannot detect or block the process.

2.3 TerminusSource CodeGitHubAddress

Https://github.com/godaddy/terminus

3. Kubernetes corresponding interface

The open port is detected using the Livenessprobe probe.

livenessprobe:          httpget:            /healthcheck      #对应应用的健康路径            port:3000                   #统一的健康检查端口, There is no port          conflict           inside the Cloud Platform 5                1
View Code

Nodejs Micro-service Health Screening Program

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.