How to Install PostgreSQL on Ubuntu and Secure It Properly

PostgreSQL is a solid choice for a web app that needs reliable transactions, strict data types, and room to grow, and setting it up on Ubuntu takes less than an hour when you follow a clear order. To install postgresql on ubuntu safely, you need more than the install command: you need a database and a user with limited rights, a login method that does not trust the network by default, a firewall that keeps the port closed, and a backup you have actually tested. This guide covers each step on Ubuntu 24.04.

How to install postgresql on ubuntu step by step

Ubuntu ships PostgreSQL in its own packages, which is fine for most projects and simple to keep updated. Install the server package and its contrib tools, then check that the service started on its own, because the package enables it during install.

sudo apt update
sudo apt install postgresql postgresql-contrib -y
sudo systemctl status postgresql --no-pager
sudo -u postgres psql -c "SELECT version();"

The version query confirms the server answers and tells you which release you are running. PostgreSQL creates a system user called postgres and a matching database role. Run admin commands as that user with sudo -u postgres psql until you have created your own admin role. If you are setting up the whole server from scratch, pair this guide with the steps in how to set up a secure Ubuntu 24.04 VPS from scratch.

Check the service and connect the first time

After install, confirm the service listens on the expected port and that local connections work. PostgreSQL listens on port 5432 by default, but on a fresh install it accepts local connections only, which is the safe default. Check the listening socket with ss -tlnp | grep 5432 and confirm the service is enabled so it restarts after a reboot. If the service is not running, read the log with sudo journalctl -u postgresql --no-pager | tail -30 before you change anything, because the log usually names the exact problem. Connect once as the postgres role, list databases with l, and quit with q.

Create a database and a user with limited rights

Your app should never connect as the postgres superuser. Create one database per app and one role for that app, give the role a strong password, and grant it rights only on its own database. The commands below create a database called myapp and a role called myapp_user, then grant that role the rights it needs to connect and work inside its own database.

sudo -u postgres psql
CREATE DATABASE myapp;
CREATE ROLE myapp_user WITH LOGIN PASSWORD 'use-a-long-random-password-here';
GRANT CONNECT ON DATABASE myapp TO myapp_user;
c myapp
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO myapp_user;

Store the password in your app config or a secrets file, never in a chat message or a public repo, and rotate it if it is ever shared. The postgresql user roles permissions model rewards small, clear grants: an app role that can only touch its own tables is far safer than a role that can create roles or drop databases. If you are still choosing between database engines, this comparison of MySQL versus PostgreSQL on a VPS with limited RAM sets out the trade-offs for a small server.

Lock down authentication

Authentication is controlled by the pg_hba.conf file, which lists which users can connect from where and by which method. Read the file before editing it. The default file trusts local socket connections for the postgres role and asks for a password over TCP. A secure postgresql ubuntu server keeps that pattern: local admin work over the socket, app connections with a SCRAM password, and no trust rule for any network address. The postgresql authentication setup worth aiming for uses scram-sha-256 for password logins, because it stores a salted hash and never sends the plain password across the connection.

# /etc/postgresql/16/main/pg_hba.conf
local   all             postgres                                peer
local   all             all                                     scram-sha-256
host    myapp           myapp_user      127.0.0.1/32            scram-sha-256
host    all             all             0.0.0.0/0               reject

After editing, reload the config with sudo systemctl reload postgresql and test a login as the app role with psql -h 127.0.0.1 -U myapp_user -d myapp. If the login fails, check the log for the exact line that rejected it, because pg_hba rules are read in order and the first match wins. Keep a backup of the file before you edit it, so a lockout takes a minute to undo.

Firewall and network access

PostgreSQL should not be reachable from the internet on a typical single-server setup. Your app and your database run on the same VPS, so the database only needs localhost. Check the listen_addresses setting and leave it at localhost unless you have a clear reason to change it. If a second server must connect, open the port only to that server IP in the firewall, require SSL, and use a strong SCRAM password. A server that exposes port 5432 to the whole internet will be found by scanners quickly and hit with password guessing. For the full hardening pass around the database, follow this checklist of 15 security steps to harden a fresh Ubuntu server.

Backups you can actually restore

Use pg_dump for a logical backup of one database, and schedule it with cron so it runs without you remembering. The command below writes a compressed backup with the date in the file name, and you should store at least one recent copy off the server, because a backup on the same disk does not survive a disk failure.

pg_dump -U myapp_user -h 127.0.0.1 -d myapp -F c -f /var/backups/myapp-$(date +%F).dump
createdb myapp_restore_test
pg_restore -U myapp_user -h 127.0.0.1 -d myapp_restore_test /var/backups/myapp-2026-11-08.dump

Run a restore test every month on a scratch database, and keep seven daily backups and four weekly ones. When the database outgrows one server, managed options are worth a look, so compare them in this guide to managed databases: RDS versus Cloud SQL versus PlanetScale.

Basic tuning for a small VPS

PostgreSQL ships with conservative defaults meant for a small machine, and a few settings are worth raising on a VPS with 2 GB or 4 GB of RAM. The main one is shared_buffers, often set to about 25 percent of RAM. Next comes work_mem, which limits the memory one sort or hash operation can use, and maintenance_work_mem, which speeds up index builds and vacuuming. Change one value at a time, restart or reload as the setting requires, and measure query times before and after so you know what helped. Settings live in /etc/postgresql/16/main/postgresql.conf, and you can check any active value from psql with SHOW shared_buffers;.

# /etc/postgresql/16/main/postgresql.conf
shared_buffers = 512MB
work_mem = 8MB
maintenance_work_mem = 128MB
effective_cache_size = 1536MB

Checks to run every month

A short monthly routine keeps a database safe without much effort. Check that the service is enabled and running, that the latest backup restored cleanly, that disk use is below 80 percent, and that no role has more rights than it needs. Apply Ubuntu security updates on a schedule, and keep a one-page note of the database names, roles, backup location, and restore steps.

Do I need the official PostgreSQL repository?

No, not for most projects. The Ubuntu package tracks a stable release and gets security updates with the system.

Can I open PostgreSQL to the internet if I use a strong password?

You can, but you should not for a normal app. Keep it on localhost, or open it to one named server IP only, with SCRAM passwords and SSL. A strong password helps, but a closed port removes the guessing attempts entirely.

Your next step is a single pass through the checklist: install, create the app database and limited role, set SCRAM auth, close the port, and schedule a nightly pg_dump with a monthly restore test.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.