Connecting to Postgresql in a docker container from outside Connecting to Postgresql in a docker container from outside docker docker

Connecting to Postgresql in a docker container from outside


You can run Postgres this way (map a port):

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres

So now you have mapped the port 5432 of your container to port 5432 of your server. -p <host_port>:<container_port> .So now your postgres is accessible from your public-server-ip:5432

To test:Run the postgres database (command above)

docker psCONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                     NAMES05b3a3471f6f        postgres            "/docker-entrypoint.s"   1 seconds ago       Up 1 seconds        0.0.0.0:5432->5432/tcp    some-postgres

Go inside your container and create a database:

docker exec -it 05b3a3471f6f bashroot@05b3a3471f6f:/# psql -U postgrespostgres-# CREATE DATABASE mytest;postgres-# \q

Go to your localhost (where you have some tool or the psql client).

psql -h public-ip-server -p 5432 -U postgres

(password mysecretpassword)

postgres=# \l                             List of databases   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges-----------+----------+----------+------------+------------+----------------------- mytest    | postgres | UTF8     | en_US.utf8 | en_US.utf8 | postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 | template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres   

So you're accessing the database (which is running in docker on a server) from your localhost.

In this post it's expained in detail.


I managed to get it run on linux

  1. run the docker postgres - make sure the port is published, I use alpine because it's lightweight.

    docker run --rm -P -p 127.0.0.1:5432:5432 -e POSTGRES_PASSWORD="1234" --name pg postgres:alpine
  2. using another terminal, access the database from the host using the postgres uri

    psql postgresql://postgres:1234@localhost:5432/postgres

for mac users, replace psql with pgcli


You can also access through docker exec command by:

$ docker exec -it postgres-container bash# su postgres$ psql

Or

$ docker exec -it postgres-container psql -U postgres