Postgresql – How to save database connection information when using `psql`


I am learning to use psql to work with a postgres database on linux.

I can connect using a long connection string, for example by running:

psql postgresql://myusername:mypassword@localhost:5433/dbname

However, I would like to save the details of my connection string somewhere, to simplify the command to connect to the database.

I've added the parameters to ~/.pgpass, and I've also changed the environment variables PGDATABSE, PGHOST, PGPORT, and PGUSER. However, I'm not sure how to tell psql to source connection information from either ~/.pgpass or the environment variables. When I just type psql I get an error, and I can tell from the details of the error that it is trying to connect using default parameters, like port 5432 instead of my specific port.

So how to I tell psql to use the parameters in ~/.pgpass or the environment variables? Or more broadly, how can I save my connection information to simplify the command to connect in the future?

Best Answer

Thanks to the comment from @a_horse_with_no_name:

Enter the details in ~/.pg_service.conf, for example:


Then set a PGSERVICE environment variable specifying which connection to use

echo PGSERVICE=myconnection

Then simply entering psql should make the connection.