PostgreSQL is a reliable relational database for web apps, analytics, and mixed workloads. This guide covers installation on Ubuntu/Debian, creating a database, and basic security.
Prerequisites
- Ubuntu 20.04+ or Debian 11+ with
sudo - At least 1 GB RAM (2 GB+ for heavier loads)
Installation
1. Update and install the server
Bashsudo apt update && sudo apt upgrade -y sudo apt install -y postgresql postgresql-contrib
2. Enable and check the service
Bashsudo systemctl status postgresql sudo systemctl enable postgresql
By default PostgreSQL listens on localhost (127.0.0.1), which fits apps on the same VPS.
Create an application user and database
Switch to the postgres system user and open psql:
Bashsudo -u postgres psql
In psql (adjust names and password):
SQLCREATE USER myapp WITH PASSWORD 'strong_password_here'; CREATE DATABASE myapp_db OWNER myapp; GRANT ALL PRIVILEGES ON DATABASE myapp_db TO myapp; \q
Test connection:
Bashpsql -h 127.0.0.1 -U myapp -d myapp_db
Typical connection string
TEXTpostgresql://myapp:[email protected]:5432/myapp_db
Security essentials
- Strong password for the application role.
- Avoid exposing PostgreSQL to the internet unless strictly required. If you must: strict firewall,
listen_addresses,pg_hba.conf, preferably VPN or tunnel. - Combine with UFW and Fail2ban for public services.
Remote access (avoid unless needed)
Edit postgresql.conf (path varies, often /etc/postgresql/*/main/):
Configlisten_addresses = '*'
In pg_hba.conf, add a restrictive line (example: single trusted IP):
TEXThost myapp_db myapp 203.0.113.50/32 scram-sha-256
Then:
Bashsudo systemctl restart postgresql
Backups
Logical dump:
Bashsudo -u postgres pg_dump myapp_db > backup_myapp.sql
Restore:
Bashsudo -u postgres psql myapp_db < backup_myapp.sql
Schedule backups (cron) to external storage.
Troubleshooting
- Peer authentication failed: use
-h 127.0.0.1for TCP, or adjustpg_hba.conf. - Connection refused: check service status and port (
5432by default).