Reputation: 1104
I have a question. I have created simple React and Spring-Boot applications and created dockerfiles for both. Spring-Boot displays some API and React makes requests to it. However, both of them works on ports (React - 3000 and Spring-Boot - 8080). When I made a request, I have my fetch sth like this:
fetch("http://localhost:8080/projects")
How am I supposed to change this, in order to work it with docker-compose? Because when I export ports in docker-compose file this fetch make requests inside the container, not outside of it.
docker-compose:
version: '3'
services:
frontend:
image: "IMAGE/FRONTEND:latest"
ports:
- "3000:3000"
depends_on:
- backend
backend:
image: "IMAGE/BACKEND:latest"
ports:
- "8080:8080"
Upvotes: 2
Views: 2642
Reputation: 18764
Here's an example docker compose that will help illustrate how you can do what you are trying to do:
version: '3'
services:
frontend:
image: "alpine:latest" #Using alpine as it has wget
command: sh -c "while true; do wget -q -S -O /dev/null http://backend:80 && sleep 4; done" #This just a sample script that get from the backend service a webpage. Note the usage of the "backend" hostname. it writes to null and only displays headers for brevity. This is just to prove that the front end can reach backend.
depends_on:
- backend
backend:
image: "nginxdemos/hello" # just a dummy image that exposes a html page over port 80
#Notice you dont need to expose ports. Look at docker compose networking for a better understanding of how these two containers are on the same n/w.
Basically like your backend I have used a niginx demo container that serves pages over port 80. For the front end I have used a shell script that just queries the back end and displays only the headers.
So in your case the problem is that your front end tries to go to localhost
for the backend. Whereas the localhost is just pointing to the front end container. You really want it to point to the hostname backend
which in turn will route you to containers in the backend service.
To understand how compose networking works please do take a look at https://docs.docker.com/compose/networking/. Relevant snippet which comes into play in the above example.
By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.
Upvotes: 1