Connecting to PostgreSQL Using PSQL Command Line Interface on Docker

In production, databases are often installed on servers using Linux or Docker. Connecting to the database through a command-line interface is the best practice as they are quick and widely accepted. In this tutorial, we will learn how to connect to PostgreSQL using PSQL, which is the default command-line interface for PostgreSQL.

Starting the Docker

To start the Docker instance, we need to locate the Docker desktop app and click on its icon.

Heading 2: Starting the Container After starting the Docker instance, we can start the PostgreSQL container. We can either use the Docker desktop app or the command-line interface. In the command-line interface, we can use the following command:

docker start postgres_img

Connecting with PostgreSQL

The default command-line interface for PostgreSQL is “psql”. We can use the following command to connect to our PostgreSQL database:

docker exec -it postgres_img psql -U postgres

Understanding Docker Exec Command

The “Docker Exec” command is used to execute commands within a running Docker container. We can use the “-it” option together, which is a combination of two options. The “-i” option tells the Docker to allocate a pseudo-TTY for the command, and the “-t” option tells the Docker to create an interactive terminal session. We need to pass the container name and the PostgreSQL default command-line interface “psql”. We can also pass the desired username using the “-U” option.

Testing the Connection

To test if we have connected to the PostgreSQL database, we can use the meta-command

Postgres=#\du 

in the PSQL command-line interface. It will show us the names of all the users available on the server.

Conclusion

In this tutorial, we learned how to connect to PostgreSQL using the PSQL command-line interface on Docker. In the next tutorial, we will learn how to connect to PostgreSQL using VS Code. Don’t forget to subscribe to our channel and turn on notifications. Thanks for reading, and have a great day!