Skip to content

Environment Variables

pg respects standard PostgreSQL environment variables when no explicit connection options are provided.

Supported Variables

Variable Description Example
PGHOST Database server host localhost
PGPORT Database server port 5432
PGDATABASE Default database name myapp
PGUSER Database username admin
PGPASSWORD Database password secret123
PGPASSFILE Password file location ~/.pgpass
PGSERVICEFILE Service file location ~/.pg_service.conf

Usage

Set environment variables in your shell:

export PGHOST=localhost
export PGPORT=5432
export PGUSER=admin
export PGDATABASE=myapp

# Now pg uses these defaults
pg query
pg dump db -f dump.sql
pg maintain vacuum

Priority Order

pg uses connection information in this order:

  1. Explicit options (-h, -p, -u, -d, -c, -s) - Cannot mix different connection methods
  2. PostgreSQL defaults

Connection Method Conflicts

Using multiple connection methods together will cause pg to fail:

# ❌ This will fail
pg query -s production -h localhost

# ❌ This will also fail
pg query -c "host=server" -u admin

Common Patterns

Development Setup

# In ~/.bashrc or ~/.zshrc
export PGHOST=localhost
export PGPORT=5432
export PGUSER=dev_user
export PGDATABASE=myapp_dev

# Simple commands without connection flags
pg query
pg dump db -f daily-dump.sql

CI/CD Pipelines

# Set in CI environment
export PGHOST=ci-database
export PGUSER=ci_user

# Scripts work without hardcoded connections
pg info ready
pg dump db -f test-data.sql

Security Notes

  • Avoid PGPASSWORD in production - use .pgpass files or certificate auth instead
  • Use service files for better credential management
  • Environment variables are visible in process lists - prefer secure alternatives

For complete PostgreSQL environment variable documentation, see the PostgreSQL documentation.