Home » Programming » Databases » How to Connect to PostgreSQL from the Linux Command Line

How to Connect to PostgreSQL from the Linux Command Line

This short tutorial will show you how to connect to a PostgreSQL database server from the Linux command line. Instructions are included for Ubuntu, Fedora, and Arch Linux.

The PostgreSQL Client – psql Command

To connect to a PostgreSQL database server from the Linux command, you need to install and use the psql program – the PostgreSQL client.

By default, when installing the PostgreSQL server on Linux, the client is also installed – but you may want to install the client without the server if you are only planning on managing a database remotely.

Installing psql on Ubuntu/Debian

To install the PostgreSQL client only on Ubuntu/Debian Linux, run:

sudo apt-get install postgresql-client

Installing psql on Red Hat/Fedora

To install the PostgreSQL client only on Red Hat/Fedora Linux, run:

sudo dnf install postgresql

Installing psql on Arch Linux

To install the PostgreSQL client only on Arch Linux, run:

sudo pacman -S postgresql-libs

Connecting to PostgreSQL from Ubuntu, Fedora, Arch, and Linux

With the client installed, you can connect to a PostgreSQL server using the psql command and specifying the host (-h), port (-p), and the name of the database (-d) to connect to.

psql -h localhost -p 5432 -d database_name

Above, psql is used to connect to the datbase named database_name hosted on the PostgreSQL server running on port 5432 on the local machine. By default, psql will try and connect to the host localhost and the default PostgreSQL port 5432, so those options could be omitted from the command.

To connect to a remote PostgreSQL server, supply a hostname or IP address:

psql -h my_database_server_hsot -p 5432 -d database_name

or:

psql -h 192.168.1.10 -p 5432 -d database_name

Supplying User Credentials when Connecting to PostgreSQL

Unless you are logged in as the user postgres and connecting to localhost, you will most likely need to specify the username (-U) and ask to be prompted for a password (-W) to connect:

psql -h localhost -p 5432 -U user_name -W -d database_name
SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment