Creating a simple ping servlet for AWS Elastic Load Balancer (ELB) Health Check

If you use the AWS Elastic Load Balancer (ELB) you’ll need to decide what to use as an endpoint on your application server for the health checker. This is how the ELB will determine if an instance is healthy, or not.

If you use the default “/” path, this may mean that a session in your application is kicked off every time the health checker connects, which could translate to unnecessary added load on your server (though perhaps it may be negligible).

Furthermore, if you create a static .html file and map it, and point the health checker to that, it could turn out that though your application server is hung, the simple static .html is still getting served. This would not make for an accurate health check, and happened to me in my experience.

The best way to ensure that your application server is online and not hung, without adding extra load to your server, will be to create a simple program that runs on the application server. In the case of a Java application server, you can create a simple servlet, as follows:

package com.whatever.aws.elb;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class Ping extends HttpServlet {
 private String message;

 public void init() throws ServletException {
  message = "Pong";
 }

 public void doGet(HttpServletRequest request,
  HttpServletResponse response)
 throws ServletException, IOException {
  response.setContentType("text/html");

  PrintWriter out = response.getWriter();
  out.println(" < h1 > " + message + " < /h1>
   ");
  }
 }

And map the servlet to a path in web.xml:

<servlet>
  <servlet-name>Ping</servlet-name>
  <servlet-class>com.perthera.elb.Ping</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>Ping</servlet-name>
  <url-pattern>/Ping</url-pattern>
  <url-pattern>/ping</url-pattern>
</servlet-mapping>

Now, you can configure the ELB health checker to connect to the “/ping” path on your instance. If it times out, or returns an error, that means the application server is not healthy. If it returns a normal HTTP code, then all is good.

Leave a Reply

Your email address will not be published. Required fields are marked *