Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access localhost and docker network using docker-compose

I have two different services running in a single docker-compose file. I talk to each service by referring to the service name of the containers.

Now I want my container A to access localhost as well. For this when I added the configuration of 'network_mode=host', but this creates an error now stating that container A cannot talk to container B.

version: '2'

services:
  rocketchat:
    image: myimage
    environment:
      - MONGO_URL=mongodb://mongo:27017/dbname
    depends_on:
      - mongo
    ports:
      - 3000:3000
    network_mode: host

  mongo:
    image: mongo:3.2
    ports:
      - 27017:27017

For each compose file docker-compose creates a network so in this case, should I manually assign the containers to a dedicated network as well? Or is there any workaround to access both the networks?

like image 860
Nirojan Selvanathan Avatar asked Jul 04 '19 07:07

Nirojan Selvanathan


People also ask

How do I connect Docker Compose to localhost?

Accessing the Host With the Default Bridge Mode You just need to reference it by its Docker network IP, instead of localhost or 127.0. 0.1 . Your host's Docker IP will be shown on the inet line. Connect to this IP address from within your containers to successfully access the services running on your host.

Can a Docker container access localhost?

If it's listening on localhost 127.0. 0.1 it will not accept the connection. Then just point your docker container to this IP and you can access the host machine!

How do I make my Docker container accessible from network?

Published ports To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host to the outside world. Here are some examples.


1 Answers

try to add links :

version: '2'

services:
  rocketchat:
    image: myimage
    environment:
      - MONGO_URL=mongodb://mongo:27017/dbname
    depends_on:
      - mongo
    ports:
      - 3000:3000
    links:
      - mongo
    #network_mode: host

  mongo:
    image: mongo:3.2
    ports:
      - 27017:27017

and you do not need network_mode: host if you use the links

EDIT - Other solution:

version: '2'

services:
  rocketchat:
    image: myimage
    environment:
      - MONGO_URL=mongodb://localhost:27017/dbname
    depends_on:
      - mongo
    ports:
      - 3000:3000
    network_mode: host

  mongo:
    image: mongo:3.2
    ports:
      - 27017:27017
    network_mode: host
like image 76
LinPy Avatar answered Oct 20 '22 07:10

LinPy