Solution
The solution to succeed API calls from local browser client-side in Docker Containers environment is…
To write 127.0.0.1 host.docker.internal
in /etc/hosts
.
Detail
When developing Web application in local machine, Docker Container is used commonly. To communicate between Docker Containers in local machine, we call APIs sometimes from the browser (Client-side) rendered by Server-side, but it will fail by original configuration.
Without thinking host domain, the baseurl(For example, axios baseURL) should be coded as localhost
. It does not work in Docker Containers environment because the domain name resolution fails. That is why we need to replace localhost
to host.docker.internal
. Refer to the official document.
This resolves the only serverside API calls communication between docker containers such as between Next.js frontend server and Node.js backend server.
However, most developers execute API calls from the browser(Client-side) rendered by Frontend serverside, but it will fail just only by replacing host.docker.internal
. The browser is finding host.docker.internal
in the local machine but it does not exist. The only docker containers understand and handlehost.docker.internal
.
The Error on the browser should be, “Failed to load resource: A server with the specified hostname could not be found.” Check it in developer tools.
We need to sort this problem up. Look at the below picture. This is the structure why we can not make API requests from a browser succeeded and is also the best answer.
One bad programmatic solution is to handle where the API domain is in the browser(Client-side), then change the baseurl host.docker.internal
to localhost
. However, it is not smart and not for production mode. host.docker.internal
is just used for development mode and on the local machine. We do not want to put the code working on only development mode.
To avoid this solution, write 127.0.0.1 host.docker.internal
in /etc/hosts
so that the API requests from the browser go to localhost(127.0.0.1) then succeed the API requests correctly.
Of course, host.docker.internal
must be written in .env
or other environment files not original source project.