I am running a project with docker compose, it consists of 2 containers: client and server
This is the current docker-compose.yaml
file:
version: "3.8"
services:
server:
build: ./server
ports:
- "80:80"
volumes:
- ./server:/app
- /app/node_modules
env_file:
- .env
client:
build: ./client
ports:
- "3000:3000"
volumes:
- ./client:/app
- /app/node_modules
depends_on:
- server
In client-side code (a Next.JS app) the HTTP requests URL is set to http://localhost:80/api/v1/
and everything works fine. I am able to access the client in the browser at http://localhost:3000
, the client fetches data from the server and renders to the user normally.
However, I wish I could make the client send requests to the server directly through the docker network, and not through localhost as a middleman, so I tried changing the URL from http://localhost:80/api/v1/
to http://server:80/api/v1/
Then I accessed the client through the browser again and, this time, as soon as the client tries to fetch data from the server, I get this error in the console:
::ERR_NAME_NOT_RESOLVED
I checked the network:
henrique@my-project$ sudo docker network ls
NETWORK ID NAME DRIVER SCOPE
6763669621ae bridge bridge local
0b26076b0be2 host host local
f4dc395426d2 my-project_default bridge local
ffa82867354a none null local
I checked the containers (services):
henrique@my-project$ sudo docker ps --format \
"table {{.ID}}\t{{.Status}}\t{{.Names}}"
CONTAINER ID STATUS NAMES
3d8727bc9ca4 Up About an hour my-project-client-1
59f75f5b39d3 Up About an hour my-project-server-1
I checked the communication between the 2 containers:
henrique@my-project$ sudo docker exec my-project-client-1 ping my-project-server-1
PING my-project-server-1 (172.30.0.2): 56 data bytes
64 bytes from 172.30.0.2: seq=0 ttl=64 time=0.060 ms
64 bytes from 172.30.0.2: seq=1 ttl=64 time=0.041 ms
64 bytes from 172.30.0.2: seq=2 ttl=64 time=0.048 ms
64 bytes from 172.30.0.2: seq=3 ttl=64 time=0.047 ms
^C
I opened a bash shell inside the client container and checked the communication with the curl command:
/app # curl http://my-project-server-1:80/api/v1/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/v1/</pre>
</body>
</html>
(it worked. This is the expected HTTP response for this endpoint)
I inspected the server container by running sudo docker container inspect my-project-server-1
and then I copied its IP address from the line: "IPAddress": "172.30.0.2",
Finally, I tried setting up the HTTP request URL to http://172.30.0.2:80/api/v1/
.
Then, this time, as soon as the client tries to fetch data from the server, the page keeps loading infinitely. There are no errors anywhere.
So, each URL presents a different behavior:
-
http://localhost:80/api/v1/
: works fine -
http://server:80/api/v1/
: throws error ERR_NAME_NOT_RESOLVED -
http://172.30.0.2:80/api/v1/
: infinite loading