When deploying Django into AWS Fargate how do you add the local ip into ALLOWED_HOSTS

Question:

I am testing out deploying my Django application into AWS’s Fargate Service.

Everything seems to run, but I am getting Health Check errors as the Application Load Balancer is sending requests to my Django application using the Local Ip of the host. This give me an Allowed Host error in the logs.

Invalid HTTP_HOST header: ‘172.31.86.159:8000’. You may need to add ‘172.31.86.159’ to ALLOWED_HOSTS

I have tried getting the Local ip at task start up time and appending it to my ALLOWED_HOSTS, but this fails under Fargate:

Is there a way to get the ENI IP Address so I can append it to ALLOWED_HOSTS?

Answer:

Now this works, and it lines up with the documentation, but I don’t know if it’s the BEST way or if there is a BETTER WAY.

My containers are running under the awsvpc network mode.

https://aws.amazon.com/blogs/compute/under-the-hood-task-networking-for-amazon-ecs/

…the ECS agent creates an additional “pause” container for each task before starting the containers in the task definition. It then sets up the network namespace of the pause container by executing the previously mentioned CNI plugins. It also starts the rest of the containers in the task so that they share their network stack of the pause container. (emphasis mine)

I assume the

so that they share their network stack of the pause container

Means we really just need the IPv4 Address of the pause container. In my non-exhaustive testing it appears this is always Container[0] in the ECS meta: http://169.254.170.2/v2/metadata

With those assumption in play this does work, though I don’t know how wise it is to do:

Of course, if we pass in the container name that we must set in the ECS task definition, we could do this too:

Either of these snippets of code would then in in the production settings for Django.

Is there a better way to do this that I am missing? Again, this is to allow the Application Load Balancer health checks. When using ECS (Fargate) the ALB sends the host header as the Local IP of the container.

Leave a Reply