Skip to content

Instantly share code, notes, and snippets.

@LegoStormtroopr
Created May 3, 2017 01:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LegoStormtroopr/7a80e170bd3943b6a37a3bd45a918a0b to your computer and use it in GitHub Desktop.
Save LegoStormtroopr/7a80e170bd3943b6a37a3bd45a918a0b to your computer and use it in GitHub Desktop.
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