How Do I Set Up PostgreSQL on a DigitalOcean Droplet?
Install and secure PostgreSQL on Ubuntu, create databases and users, and connect your app to a database on DigitalOcean.
Self-Hosted vs Managed Database
DigitalOcean offers Managed PostgreSQL (fully maintained, automated backups, high availability), but running PostgreSQL on your own Droplet gives you full control and lower cost for small projects. This guide covers the self-hosted approach.
Step 1 — Install PostgreSQL
sudo apt update
sudo apt install postgresql postgresql-contrib -y
sudo systemctl enable postgresql
psql --version
Ubuntu installs the latest PostgreSQL version available in its repos (typically PostgreSQL 16).
Step 2 — Create a Database and User
sudo -u postgres psql
CREATE USER myapp WITH PASSWORD 'strong_password_here';
CREATE DATABASE myapp OWNER myapp;
GRANT ALL PRIVILEGES ON DATABASE myapp TO myapp;
\q
Step 3 — Configure Remote Access (Optional)
By default, PostgreSQL only accepts local connections — which is the secure default. If your app runs on the same Droplet, skip this step. To allow connections from another Droplet:
Edit /etc/postgresql/16/main/postgresql.conf:
listen_addresses = 'localhost,10.0.0.5'
Edit /etc/postgresql/16/main/pg_hba.conf and add:
host myapp myapp 10.0.0.0/24 scram-sha-256
sudo systemctl restart postgresql
Restrict access to your private network or specific IPs via DigitalOcean Cloud Firewalls.
Step 4 — Connect from Your Application
DATABASE_URL=postgres://myapp:strong_password_here@localhost:5432/myapp
Test the connection:
psql -U myapp -d myapp -h localhost
Step 5 — Basic Maintenance
# Backup
pg_dump -U myapp myapp > backup.sql
# Restore
psql -U myapp myapp < backup.sql
# Check database size
psql -U myapp -c "SELECT pg_size_pretty(pg_database_size('myapp'));"
Security Checklist
- Use strong passwords — never leave the default postgres user unsecured
- Bind to localhost unless remote access is required
- Block port 5432 in Cloud Firewalls for public-facing Droplets
- Schedule automated backups with cron and pg_dump
When your project outgrows a single Droplet, migrate to DigitalOcean Managed PostgreSQL for automated failover and point-in-time recovery.