Connecting to PostgreSQL in a Docker Container from Outside

Running PostgreSQL in a Docker container is a convenient way to set up and manage your database environment. But by default, PostgreSQL inside Docker isn’t accessible from outside the container — you need to configure networking and authentication to allow external connections.

In this guide, we’ll go step-by-step through connecting to PostgreSQL in a Docker container from your local machine or another service.


1️⃣ Run PostgreSQL Container with Port Mapping

The key to accessing PostgreSQL from outside the container is publishing the container’s PostgreSQL port (5432) to your host machine.

Example:

docker run --name my_postgres \
  -e POSTGRES_USER=myuser \
  -e POSTGRES_PASSWORD=mypassword \
  -e POSTGRES_DB=mydb \
  -p 5432:5432 \
  -d postgres

Explanation:

  • -p 5432:5432 → Maps container port 5432 to host port 5432.
  • POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB → Set up initial credentials and database.

2️⃣ Allow External Connections in PostgreSQL

By default, PostgreSQL inside Docker listens only on localhost. To connect externally, ensure it listens on all network interfaces.

  1. Access the container shell: docker exec -it my_postgres bash
  2. Edit postgresql.conf (usually in /var/lib/postgresql/data): listen_addresses = '*'
  3. Edit pg_hba.conf to allow remote connections: host all all 0.0.0.0/0 md5
  4. Restart PostgreSQL inside the container: pg_ctl restart or restart the container: docker restart my_postgres

3️⃣ Connect from Host Machine

Once configured, you can connect from your local machine using:

psql -h localhost -p 5432 -U myuser -d mydb

It will prompt for the password (mypassword).

You can also use a GUI client like pgAdmin, DBeaver, or TablePlus:

  • Host: localhost
  • Port: 5432
  • User: myuser
  • Password: mypassword
  • Database: mydb

4️⃣ Connect from Another Container

If another container needs to connect to this PostgreSQL instance:

  • Put both containers on the same Docker network: docker network create my_network docker network connect my_network my_postgres docker run --network=my_network ...
  • Use the container name (my_postgres) as the host: psql -h my_postgres -U myuser -d mydb

5️⃣ Common Troubleshooting Tips

  • Port already in use:
    If 5432 is taken, map to another host port: -p 5555:5432 Then connect with: psql -h localhost -p 5555 ...
  • Firewall blocking connections:
    Ensure your system firewall allows traffic on the mapped port.
  • Authentication failures:
    Double-check credentials and pg_hba.conf rules.

📌 Summary

To connect to PostgreSQL in a Docker container from outside:

  1. Publish the PostgreSQL port using -p.
  2. Configure listen_addresses and pg_hba.conf for external access.
  3. Connect via psql, GUI tools, or other containers.

With these steps, your PostgreSQL container becomes accessible for local development or inter-service communication.

Sharing Is Caring:

Leave a Comment