Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to Postgresql in a docker container from outside

I have Postgresql on a server in a docker container. How can I connect to it from the outside, that is, from my local computer? What setting should I apply to allow that?

like image 656
Sojo Avatar asked Jun 08 '16 06:06

Sojo


People also ask

How do I access a docker container externally?

To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host to the outside world.


1 Answers

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 ps CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                     NAMES 05b3a3471f6f        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 bash root@05b3a3471f6f:/# psql -U postgres postgres-# 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.

like image 58
lvthillo Avatar answered Nov 09 '22 03:11

lvthillo