Postgresql – connecting to Postgres running inside docker container ‘posgres’ does not exist

dockerpostgresqlpsql

I want to connect to Postgres (running in a container) using psql

What I've done:

docker pull postgres
docker run -p5432:5432 --name mydb -e POSTGRES_PASSWORD=pass123 -d postgres

Trying to connect via PSQL command
psql -h localhost -U postgres

But I keep getting psql: FATAL: role "docker" does not exist
(I tried different variations of the command like with -d postgres or with -W , even tried with PgAdmin …still same error)

However, when I jump into the container docker exec -it mydb bash then psql -U postgres I can see the following:

postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

postgres=# \c postgres
You are now connected to database "postgres" as user "postgres".
postgres=# \l
                                 List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
-----------+----------+----------+------------+------------+-----------------------
 postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
 template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
           |          |          |            |            | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
           |          |          |            |            | postgres=CTc/postgres
(3 rows)

Best Answer

Found the issue:

I had PSQL installed locally (via brew) which was showing the error message.

Uninstalled it. Then used PgAdmin to connect to the container. And it's working fine now.