Search code examples
postgresqldockermanjaro

Ports forwarding does not work for docker postgres


I want to set up a docker container with postgres database. To do this I use the following command:

sudo docker run --name postgres-demo -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres

Container starts and runs ok. I can use docker exec in it and run psql inside container. Something is wrong with ports forwarding. When I try to execude command psql on my machine (outside container), I get a message: psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

My operating system is Manjaro 21.2.6.


Solution

  • You must specify the hostname of postgre. The hostname of a container is usually 0.0.0.0.

    $ psql --help
      ...
      -h, --host=HOSTNAME      database server host or socket directory (default: "local socket")
    
    $ docker ps
    CONTAINER ID   IMAGE      COMMAND                  CREATED         STATUS         PORTS                                       NAMES
    605b59525844   postgres   "docker-entrypoint.s…"   3 minutes ago   Up 3 minutes   0.0.0.0:5432->5432/tcp, :::5432->5432/tcp   postgres-demo
    
    $ psql --host=0.0.0.0 --username=postgres
    Password for user postgres: 
    psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1), server 14.2 (Debian 14.2-1.pgdg110+1))
    WARNING: psql major version 12, server major version 14.
             Some psql features might not work.
    Type "help" for help.
    
    postgres=#