PostgreSQLConnecting to a Database

Connecting to a Database

Every PostgreSQL client — psql, pgAdmin, or a driver inside your application code — needs the same handful of pieces of information to establish a connection. Once you understand these parameters, connecting from any tool or language follows the same pattern.
Connection parameters

Parameter

Meaning

Typical default

host

Server address (hostname or IP) to connect to

localhost

port

TCP port the server is listening on

5432

database

Name of the database to connect to

same as username

user

Role/username to authenticate as

postgres

password

Password for that role

(none — set at install)

Connection strings (URIs)
Rather than passing every parameter as a separate flag or option, most tools and drivers accept a single connection URI that bundles everything together:

Connection URI format

Bash
postgresql://user:password@host:port/dbname

A concrete example

Bash
postgresql://app_user:s3cret@localhost:5432/app_production

This single-string format is especially convenient for configuration files and environment variables, since you only need to manage one value instead of five.

Environment variables
PostgreSQL client tools (including psql itself) automatically recognize a set of standard environment variables. If these are set, you can omit the corresponding flags entirely:

Variable

Corresponds to

PGHOST

host

PGPORT

port

PGUSER

user

PGPASSWORD

password

PGDATABASE

database

Connecting using environment variables

Bash
export PGHOST=localhost
export PGUSER=app_user
export PGPASSWORD=s3cret
export PGDATABASE=app_production

psql
Connecting from application code
Every major programming language has one or more mature PostgreSQL drivers — for example node-postgres and Prisma for Node.js, psycopg2 for Python, pg gems for Ruby, and JDBC drivers for Java. All of them ultimately accept the same host/port/database/user/password parameters, usually via a connection string.
Never hardcode credentials
Do not write database usernames or passwords directly into your application’s source code. Load them from environment variables, a .env file excluded from version control, or a dedicated secrets manager. Hardcoded credentials are one of the most common — and most preventable — causes of database breaches.
  • Store connection details in environment variables or a secrets manager, not in code

  • Use different credentials for development, staging, and production

  • Grant application roles only the privileges they actually need — avoid connecting as a superuser from application code