Home > OS >  Connecting two containers MongoDB Python project
Connecting two containers MongoDB Python project

Time:03-01

I'm trying to connect two containers, one of them is using pymongo and I want to connect from inside one container, to the second, I am able to connect to it from the machine I'm running the docker on, but I can't connect from one container to another, I've tried every solution possible, but I'm sure I'm missing something:

docker-compose.yaml

version: "3"
networks:
  shared:
    driver: bridge

services:
  application:
    environment:
      ....
    image: application:latest
    ports:
      ....
    volumes:
      ....
    depends_on:
        - mongo
    networks:
      - shared
  mongo:
    image: mongo:4.2-bionic
    ports:
        - "27017:27017"
    networks:
    - shared

connection:

def get_connection():
    client = MongoClient('localhost', 27017)
    database = client.database.beacons
    return database

error:

Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 621d188d8169b99b9cfc4c5e, topology_type: Unknown, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]>

CodePudding user response:

Containers in a docker-compose network are referenced by their service name, so in your pymongo connection use:

client = MongoClient('mongo', 27017)
  • Related