14

I am trying to use docker-compose with my django-rest app. When I run it myself python manage.py runserver it works well.

If I am trying to use docker-compose sudo docker-compose up it also runs the server but when I open the page in the browser I get an error.

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused

I already have db, so I am just using this lines in settings.py

MONGODB_DATABASES = {
    "default": {
        "name": 'api',
        "host": 'localhost',
       "port": 27017
    },
}

Here is my Dockerfile:

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY . /code
RUN pip install -r requirements.txt

My docker-compose.yml:

version: '3.0'
services:
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
  mongo:
    image: mongo

Already tried this:

Pymongo keeps refusing the connection at 27017

Oleksandr Baranov
  • 528
  • 2
  • 6
  • 23

4 Answers4

5

By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

According to the docker-compose.yaml file, mongo container is accessible on mongo:27017 from web container, so settings.py should be changed to:

MONGODB_DATABASES = {
    "default": {
        "name": 'api',
        "host": 'mongo',
       "port": 27017
    },
}
nickgryg
  • 25,567
  • 5
  • 77
  • 79
1

I had the same problem.

The issue was that I used the wrong port forwarding and had an old container which was stopped but not removed.

I restarted the old container. Now it's working fine.

joran
  • 169,992
  • 32
  • 429
  • 468
1

As described in the other answers the problem is related to the mongo container name in the docker-compose.yml file so the Django settings must be changed to find the correct database host.

In later versions Djongo changed the DATABASE options in the settings.py. This will result in the following new settings.py part:

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'api',
        'CLIENT': {
            'host': 'mongo',
            'port': 27017,
        }
    }
}

Notice that host and port are now childs of CLIENT.

More information can be found in the Djongo documentation.

mhellmeier
  • 1,982
  • 1
  • 22
  • 35
0

What worked for me was simply list all the containers with

docker ps -a

CONTAINER ID        
q624462b055d        
f9324d078256        
r0888c63d21d        
tf5a32702bee        
e68d1ae9b74c

and delete the mongodb related ones using their IDs

docker rm q624462b055d f9324d078256

and change the host and port in the docker-compose file with

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'mongo,',
        'HOST': 'mongo',
        'PORT': 27017,
    }
}
Zarrie
  • 325
  • 2
  • 16