15
votes

I've started my docker image as follows:

docker run --name fnf-postgis -e POSTGRES_DB=fnf -e POSTGRES_USER=fnfuser -e POSTGRES_PASSWORD=fnf2pwd -p5432:5432 -d mdillon/postgis:11

and i've set up my django db config:

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'fnf',
        'USER': 'fnfuser',
        'PASSWORD': 'fnf2pwd',
        'host': '',
        'port': 5432,

However, running makemigrations give this error:

psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

but I can successfully connect to the container from pycharm

enter image description here

3
please show your pycharm database conecction settings.Brown Bear
@BearBrown doneTjorriemorrie
try to change the 'host' to 'localhost' instead of empty stringeran
I am not sure but don't you have to specify localhost in your 'host' ?Michał Krzywański
I've tried, localhost and 0.0.0.0, but nothing works.Tjorriemorrie

3 Answers

6
votes

As per psycopg2's documentation. If the host value is empty then by default it will look for the Unix Socket file of Postgres.

And in your error message, it is mentioned that it is looking for the socket file (.s.PGSQL.5432) under the tmp directory.

If you are running postgres as a seperate container, then you can find out this socket file under /var/run/postgresql directory in your container.

You can mount this folder to your host like below:

docker run -e POSTGRES_PASSWORD=mysecretpassword -v /home/username/socket_dir:/var/run/postgresql -d postgres

then you can update your DATABASE object like below:

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'fnf',
        'USER': 'fnfuser',
        'PASSWORD': 'fnf2pwd',
        'host': '/home/username/socket_dir/',
        'port': 5432,

Now the connection should be established.

0
votes

There is a difference between your Pycharm and your Django settings.

Pycharm explicitely connects to localhost when Django setting is trying to connect to ''.

Simply putting 'localhost' as your HOST Django setting should work.

Please note that the correct setting names are uppercase HOST and PORT, not lower case host and port.

0
votes

You should provide name of postgresql docker container as value to host key:

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'fnf',
        'USER': 'fnfuser',
        'PASSWORD': 'fnf2pwd',
        'HOST': 'fnf-postgis', # Name of postgres docker container
        'PORT': 5432, # Its exposed port
    }
}