Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handling AWS-ELB terminating a healthy django instance when accessed from an invalid hostname

Handling AWS-ELB terminating a healthy django instance when accessed from an invalid hostname

When spinning up a new service, Amazon Elastic LoadBalancer needs to check if the service is live and running. This check is done from an IP (from any IP in a private IP range) to the service, this is done by the ELB just doing a simple GET request to a specified path, with no host information - for example GET /heatbeat.

If this instance is a Django service, regardless of the page accessed, this call will fail as in a properly setup Django it is very unlikely that the IP will be in Django's settings.ALLOWED_HOSTS settings.

There are two ways around this, either:

a. Add every IP from every private IP range into your Django project's ALLOWED_HOSTS settings b. Add a simple middleware that returns a simple 200 response, given the specific URL.

The second option is shown below.

from django.http import JsonResponse
class AllAllowedHostsHealthCheckerMiddleware(object):
def process_request(self, request):
if request.path == '/heartbeat':
service_status = {
"message": "Everything is awesome",
}
return JsonResponse(service_status, status=200)
# The HealthChecker middleware *must* come first, as other middleware,
# such as `django.middleware.security.SecurityMiddleware`, may reject
# the request for its invalid HOST.
MIDDLEWARE_CLASSES = [
'healthchecker_middleware.AllAllowedHostsHealthCheckerMiddleware',
# ... everything else
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment