PostgreSQL: Change default port used by utilites like psql, createdb, etc

command linepostgresqlpsql

I have 2 instances of PostgreSQL running on some servers. One on the default port (5432) and the other instance on port 5433. Some users (and processes) only need access to the second instance (5433) and I'd like to set it up so that when those users use commands like psql or createdb in their shell it will automatically direct them to the right Postgres instance instead of them having to type -p 5433 along with every command.

I tried to look this up on www.postgresql.org but was unable to find it…probably my fault. Anyone know how?

Best Answer

PostgreSQL command-line utilities (and more generally all programs that rely on the libpq library) automatically use the environment variables PGPORT and PGHOST when they're defined.

So if you do in the shell:

$ PGPORT=5433; export PGPORT

any subsequent call to psql will act as if it has been invoked with the -p 5433 command-line option.

See Environment Variables in the libpq documentation for all these variables . They can be used to provide default values to almost every parameter of a connection to the database.