When deploying a Django application to an EC2 instance (or ECS, etc) that is behind an Elastic Load Balancer you will run into some issues with the ELB health checks. They way a health check works is that a certain url path is checked by the ELB, if the application returns HTTP code 200 the application is marked as healthy.
The problem is that your Django application will be configured with a number of ALLOWED_HOSTS that determine on what hostnames Django will ‘answer’. Off course, the ELB health checks won’t use your configured hostname but will be visiting the EC2 instance’s IP address.
By adding the snippet below we can query the AWS instance metadata and get the local IPv4 address, which we add to the ALLOWED_HOSTS setting.
EC2_PRIVATE_IP = None
EC2_PRIVATE_IP = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text