I'm facing an issue to access one container route in another container. For example i have two micro services called user-service and api-gateway. I'm trying to access user-service route in api-gateway.
My api-gateway file could be like below
const userServiceProxy = httpProxy(http://localhost:8093);
this.app.post('/admin/register', async(req, res) => {
userServiceProxy(req, res);
});
api-gateway is running on port 8080
My user-service file could be like below
app.post('/admin/register', function (req, res) {
res.send('POST request')
})
when i access route through api-gateway with the port 8080 i couldn't able to call the route but when i tried to access with the port 8093 i can able to see the result.
My docker-compose file could be like below
version: '3'
services:
api-gateway:
container_name: api-gateway
build: './api-gateway'
ports:
- "8080:8080"
links:
- user-service
user-service:
build: ./user-service
container_name: user-service
ports:
- "8093:8093"
Any help would be greatly appreciated, Thanks in advance!
localhost refers to the localhost inside the container, not the host system.
Use Docker Networks and replace localhost with the service name like api-gateway.
If the containers are in the same network the address http://api-gateway:8093should work.
Another way is to run the Container on network mode host. This is less isolation but then the address localhost works because the container is now running on the interface of the docker deamon
just add a network specification to you docker-compose file to use a custom bridge network.
something like that might work for you
version: '3'
services:
api-gateway:
container_name: api-gateway
build: './api-gateway'
ports:
- "8080:8080"
networks:
- mynet
user-service:
build: ./user-service
container_name: user-service
ports:
- "8093:8093"
networks:
- mynet
networks:
mynet:
driver: bridge
ipam:
driver: default
according to your specified ports and services in your docker-compose the following connections are now possible:
user-service:8093 api-gateway:8080if i get it right, your api-gateway would now be:
const userServiceProxy = httpProxy(http://user-service:8093);
this.app.post('/admin/register', async(req, res) => {
userServiceProxy(req, res);
});
inside a docker network you can access the ports from other containers directly (no need to specify a port-mapping to your host). probably one of your port-mappings is therefore unnecessary. if you are accessing the user-service only via api-gateway and not directly you may remove the port specification in your docker-compose files (user-service block). your user-service would then be accessible only using the api-gateway. which is probably what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With