Monday 17 August 2020

Calling API from another Docker container returning a 'Cannot assign requested address' Error

This article is to document an issue I had recently that was caused by having two docker installation on my local computer and using them as API’s to each other. Doing this means you cannot call localhost like we would have previously. I found the issue quite hard to search for because at first I was unaware it was the Docker containers that were at fault. At first I had Drupal 7 website running locally and it would call my API ( Django ) , which was on another server.

However it made sense for development to have both things on my local environment; they would both be Docker installations. On doing so I'd set the Django API up on http://localhost:8000/ which I could see worked and could connect to using Postman. However when I tried to make the request through Drupal I would get the error 'Cannot assign requested address' Basically You cant use localhost for something within a container…

Each container thinks it is an entire server in its own right, and sees ‘localhost’ as only the container, and not the host. To fix this I did the following . On the Django ( API ) side open docker-compose.yml

Add "host.docker.internal" to the list of ALLOWED_HOSTS

for example.

1 - 'ALLOWED_HOST={"hosts": ["localhost", "api.localhost", "api.docker.localhost", "host.docker.internal"]}'

This was diagnosed by viewing the logs of the fafeapi container with docker-compose logs -f fafeapi  and seeing:
Also thank you to this post https://medium.com/it-dead-inside/docker-containers-and-localhost-cannot-assign-requested-address-6ac7bc0d042b

No comments: