Reputation: 2064
I'm trying to execute a django project on my local machine, the project requires Postgres.
I know close to nothing of docker. I pulled postgres image from docker hub and executed the followin command, as suggested by the instructions in postgres docker hub page.
$ docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres
The docker container is up:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
402180487f68 postgres "docker-entrypoint.s…" 2 hours ago Up 2 hours 5432/tcp some-postgres
But I can't make Django to connect to it. (Django is running on my local machine, not on docker) Django settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'mysecretpassword',
'HOST': 'localhost',
'PORT': 5432,
}
}
If I execute migrations with the settings above the error is:
django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
I assume the connection is not beign refused, because if I stop the container the error is the same.
Some tutorial/answer suggested HOST should be the container name. To me it doesn't make much sense, as I don't know how Django is supposed to resolve that, but I tried nonetheless:
'HOST': 'some-postgres',
The error raised is:
django.db.utils.OperationalError: could not translate host name "some-postgres" to address: nodename nor servname provided, or not known
I have checked several questions and tutorials, but they all seem to use docker-composer and/or have the django project also inside docker. Still haven't been able to make the project connect to postgres.
Upvotes: 2
Views: 267
Reputation: 3076
I believe you have to forward port 5432 from the docker: https://docs.docker.com/config/containers/container-networking/#published-ports
Good analogy is a webserver - imagine you would start a django application in a container on port 8000. You couldn't just simply open firefox and navigate to localhost:8000 from within the host as the application is running in an isolated environment.
Upvotes: 1