How to connect to PostgreSQL running in a docker container from outside?

Better Stack Team
Updated on April 14, 2023

To connect to PostgreSQL running in a Docker container from outside the container, you need to expose the PostgreSQL port and provide the necessary authentication credentials. Here are the steps:

  1. When starting the PostgreSQL container, you need to expose the port that PostgreSQL is listening on. This can be done by specifying the p flag followed by the host port and container port mappings. For example:

     
    docker run -d -p 5432:5432 --name postgres postgres
    

    This will start a new PostgreSQL container with the port mapping of 5432:5432, exposing PostgreSQL port 5432 to the host.

  2. Once the container is running and the port is exposed, you can connect to PostgreSQL from outside the container using any PostgreSQL client such as psql. The syntax is as follows:

     
    psql -h <host> -p <port> -U <username> -d <database>
    

    Where <host> is the IP address or hostname of the host running the container, <port> is the host port that maps to the container port (5432 in our example), <username> is the PostgreSQL username, and <database> is the name of the PostgreSQL database.

    For example, if the host IP address is 192.168.0.100 and the PostgreSQL username is postgres, you would run:

     
    psql -h 192.168.0.100 -p 5432 -U postgres -d mydatabase
    

    This will connect to the PostgreSQL server running in the Docker container, using the specified database and authentication credentials.

    Note: By default, the postgres user does not have a password set. If you have set a password for the postgres user, you need to include the -W flag followed by the password when connecting to PostgreSQL. For example:

     
    psql -h 192.168.0.100 -p 5432 -U postgres -W -d mydatabase
    

    This will prompt you for the password before connecting to the PostgreSQL server.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack