Home > Net >  Docker connect to localhost on a another container
Docker connect to localhost on a another container

Time:09-01

I have 2 containers one running on localhost:3001 and the other on localhost:3003

container localhost:3001 hits an endpoint thats running in the container localhost:3003 But gets a (failed)net::ERR_EMPTY_RESPONSE

I have tried multiple ways to get them to connect. Please don't tell me to setup a docker compose file. I should be able to spin up 2 containers and have them communicate with their ports.

I also tried adding a network.

docker network create my-network

Shows as: ea26d2eaf604   my-network   bridge    local

Then I spin up both containers with the flag --net my-network. When container localhost:3001 hits an endpoint thats running in the container localhost:3003 again I get a (failed)net::ERR_EMPTY_RESPONSE

This is driving me crazy. What am I doing wrong here ?

I have even used shell to run a curl from localhost:3001 to localhost:3003 and I get

to curl: (7) Failed to connect to localhost port 3003 after 0 ms: Connection refused

CodePudding user response:

When you place both machines on the same network, they are able to reference each other by their service/container name. (not localhost - as localhost is a local loopback on each container). Using a dedicated network would be the ideal way to connect from container to container.

I suspect what is happening in your case is that you are exposing 3001 from container a on the host, and 3003 from container b on the host. These ports are then open on the host, and from the host you can use localhost, however, from the containers to access the host you should use host.docker.internal which is a reference to the host machine, instead of using localhost

Here is some further reading about host.docker.internal https://docs.docker.com/desktop/networking/#use-cases-and-workarounds-for-all-platforms

Update: docker-compose example


version: '3.1'

services:
  express1:
    image: node:latest
    networks:
      - my-private-network
    working_dir: /express
    command: node express-entrypoint.js
    volumes:
      - ./path-to-project1:/express

  express2:
    image: node:latest
    networks:
      - my-private-network
    working_dir: /express
    command: node express-entrypoint.js
    volumes:
      - ./path-to-project2:/express
  
networks:
  my-private-network:
    driver: bridge
    ipam:
      config:
        - subnet: 172.31.27.0/24

Then you can reference each container by their service name, e.g: from express1 you can ping express2

  • Related