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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github