Connecting to a Database
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)
Connection URI format
postgresql://user:password@host:port/dbname
A concrete example
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
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
export PGHOST=localhost export PGUSER=app_user export PGPASSWORD=s3cret export PGDATABASE=app_production psql
Connecting from application code
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..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