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
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
},
}
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.
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.
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