Reputation: 11
I just started working with docker-compose and am stuck in communication between the two services.
I have 2 services: angular and json. I want to get some data from json to angular app. As far as I understood, services should be able to reach each other by using the servicename as hostname.
Unfortunately, angular cant reach json on http://json-server:3000.
What am doing wrong? Is it even possible to make http requests between services?
This is my docker-compose.yml file:
version: '3'
services:
json-server:
image: json-server-image:latest
ports:
- "3000:3000"
container_name: json-server
hostname: json-server
angular:
image: angular-image:latest
ports:
- "8888:80"
links:
- json-server
container_name: angular
Upvotes: 1
Views: 3403
Reputation: 158977
Your Angular code doesn't run in Docker. The container named angular
probably provides an HTTP service that can provide the actual Angular code, but the code itself runs in the browser, outside of Docker. The browser doesn't know anything about Docker networking and can't directly access the network stack.
From the browser's point of view, you need to access the back-end service using the host name of the system it's running on, and the externally published (first) ports:
number. If the browser and containers are running on the same system, the host name could be localhost
, so http://localhost:3000/api/...
.
A standard technique for avoiding needing to actually know the host name is to run a reverse proxy, such as an nginx
container, that can forward to both containers. That would use the Docker-internal hostnames and the internal port numbers in its configuration, http://json-server:3000
and http://angular:80
. From the browser point of view both would be on the same host and port, and a path-only relative URL /api/...
would go to that same server.
Upvotes: 3
Reputation: 1176
Try this:
version: '3'
services:
json-server:
image: json-server-image:latest
ports:
- "3000:3000"
container_name: json-server
hostname: json-server
networks:
- some-net
angular:
image: angular-image:latest
ports:
- "8888:80"
container_name: angular
networks:
- some-net
networks:
some-net:
driver: bridge
Basicaly, the following code create a user defined docker bridge network.
networks:
some-net:
driver: bridge
Adding the following lines to each service links them together in the same network.
networks:
- some-net
Must Read: User defined bridge v/s default bridge network
Upvotes: 0