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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With