Docker - send HTTP request from one container to another
I am unable to send an HTTP request to the backend container when I run the application on the AWS server. However, when I run the application locally, I can make requests to the backend just fine. I use fetch to execute queries:
fetch('http://localhost:8000/something')
This is how the project structure looks like:
.
βββ docker-compose.yml
|
βββ backend
β βββ Dockerfile
β βββ server.js
|
βββ frontend
βββ Dockerfile
βββ package.json
βββ public
β βββ index.html
βββ src
βββ components
βββ data
βββ index.js
βββ routes.js
βββ static
βββ tests
βββ views
docker-compose.yml:
version: '3'
services:
frontend:
build:
context: .
dockerfile: frontend/Dockerfile
volumes:
- ./frontend:/frontend
ports:
- "80:5000"
links:
- backend
backend:
build:
context: .
dockerfile: backend/Dockerfile
volumes:
- ./backend:/backend
ports:
- "8000:8000"
Docker file in frontend:
FROM node:latest
RUN mkdir -p /frontend
WORKDIR /frontend
ADD . /frontend
VOLUME ["/frontend"]
EXPOSE 5000
CMD yarn && yarn build && yarn global add serve && serve -s build
Dockerfile to backend:
FROM node:latest
RUN mkdir -p /backend
WORKDIR /backend
ADD . /backend
VOLUME ["/backend"]
EXPOSE 8000
CMD yarn && yarn start
Can someone explain to me what is wrong with my config? I am very confused because it works locally without any problem.
source to share
TL; DR: need to change external code to call current host instead of "localhost"
The problem is that your application says "hey localhost" instead of "hey VPS ip" when visiting your browser. You need to change your external code to visit the current host you are visiting. This is why you are getting a request to your local server.
fetch("http:///localhost:8000/something")
Change it to instead fetch("http://"+location.host+":8000")
(There are better ways this is done).
Also note that docker containers are slightly different in terms of networking. A docker container has no concept of "localhost" in the same way that docker docker applications do. When making a server-to-server call, you need to use the IP address / IP address of the VPS. The trick I'm using is using docker default docker0 bridge 172.17.0.1.
I usually use networks on top of "links" and in fact cannot fully comment them out, but when containers are on the same docker network, you can access a different container using the container name. This only works for server-side code, i.e.: node.js server -> node.js server / mongo db. For example, a mongodb connection will be mongodb://mongo_server:27017/mydatabase
, and mongo_server will resolve the container's IP.
Another thing you might come across when trying to use an IP is your firewall, you will also have to allow that specific ip / port through your firewall.
source to share