Skip to main content
Servers Are Up
Virtual Datacenter
PricingFree Tools
Sign inBrowse catalog
Servers Are Up
Virtual Datacenter
PricingFree Tools
Sign inBrowse catalog

Loading…

Servers Are Up

Your apps, automation and data on hardware we own. Build a private stack with predictable capacity and access through your dashboard, API or SSH.

SLA with service creditsOwned hardwareUS-based

Make room for your next idea

Explore the capacity, apps and access options that fit your workload. Check current availability and your total before you buy.

Sign up freeView Pricing

Products

  • Linux VPS
  • Windows VPS
  • Cloud & SaaS Services
  • Cloud Storage (Azure)
  • Virtual Datacenter
  • AI & Agent Hosting
  • Containers
  • Instant Apps
  • Software Platforms
  • Network builder
  • Game Servers
  • Free Game Servers
  • Pricing

Resources

  • Free Network Tools
  • 2026 Pricing Benchmark
  • Live SVG Badges
  • Latency & Speed Test
  • Guides & Tutorials
  • Documentation
  • API Reference
  • MCP Server
  • CLI & SDKs
  • OpenAPI & llms.txt
  • Use Cases
  • Free Migration
  • Uptime & Reliability
  • Datacenter
  • System Status
  • Network
  • Provider Comparisons Hub
  • Compare Providers

Company

  • About Us
  • Enterprise
  • Security Architecture
  • Trust Center
  • Blog
  • FAQ
  • Compliance
  • Startup Program
  • Open-Source Sponsorship
  • Press & Media Kit
  • Referral Program
  • Help Center
  • Contact Us
© Servers Are Up
TermsPrivacySLARefund PolicyDPAAcceptable Use
Service information
Docs
  • Documentation Hub
  • Technical Knowledge Library
    Runbooks & 187 Blueprints
  • Choose a Product
    VMs, Containers & Cloud
  • First Linux Server
    SSH, Firewall & Apps
  • Windows Server 2025
    BYOL & Remote Desktop
  • Remote Access
  • Troubleshooting
  • FAQ
  • All Product Guides
    29 Step-by-Step Guides
  • Cloud & SaaS Catalog
    112 Cloud & SaaS Offerings
  • Azure Cloud Storage
    Hot/Cool/Archive & WORM
  • Resource Manager & RBAC
    Groups, Tags & Locks
  • Multi-Model Cloud DB
    JSONB, SQL & pgvector
  • Cloud Identity & ZTNA
    OIDC, SCIM & PIM
  • Key Vault & KMS
    Secrets & Envelope Keys
  • Cloud SIEM, SOAR & DLP
    Posture & Threat Response
  • API Gateway & Cloud DNS
    Edge WAF & DNS Zones
  • Serverless, Workflows & IoT
    Functions, Queues & DAGs
  • SaaS, Governance & Vault
    Budgets & Off-Host GRS
  • Linux Systems & Kernel
    SSH, UFW, sysctl & OOM
  • Self-Hosted Apps & Stacks
    Caddy, Nextcloud & Auth
  • Build Web Apps with AI
  • Next.js and React
  • TypeScript and Node.js
  • npm and Tooling
  • Data and APIs
  • Deploy and Operate
  • Tutorials
  • Infrastructure
  • Automation & Regions
  • API Overview
  • API v1 Reference
    Endpoints & 23 Scopes
  • MCP Server
    129 AI Agent Tools
  • Swagger / OpenAPI 3.1
  • API Playground
  • Versioning & Sunset
  • API Token Security
    Authentication & Tokens
  • Instances API
    Compute Resources
  • Networking API
    Networks & Ports
  • Storage API Availability
    Volumes & Backups
  • Webhooks & Events
    Event Notifications
  • Rate Limits & Best Practices
    Throttling & Retries
  • sau CLI Reference
    34 Commands (v0.2)
  • Browser Web CLI
  • SDKs
  • Infrastructure as Code
    Terraform & Ansible
  • Code Examples
  • CLI & SDK Guides
  • Security Guides
  • Security at a Glance
  • Zero Trust Architecture
  • Live Trust Center
  • Compliance
Need help?

Loading documentation...

Documentation/data apis

Set up PostgreSQL for a web app on Ubuntu 24.04

Give an application its own PostgreSQL user and database with a connection limit, connect to it, and back it up nightly with a restore you have tested.

Intermediate
25 min
Updated 2026-10-27

Deploy Ready-to-Run Infrastructure in Seconds

Linux VMs from $6/mo · Pooled Virtual Datacenters from $12/mo · Use code WELCOME20 for 20% off your first order.

Browse ServersView Pricing

Commands checked on 2026-10-27 with PostgreSQL 16, Ubuntu 24.04.

What you will have at the end

PostgreSQL running on your server, with one user and one database that belong to your application and nothing else, a cap on how many connections that user can hold, and a backup of the database written every night. You will have restored one backup into a second database and counted its rows, so you know the backups work.

Before you start

  • An Ubuntu 24.04 server with a user that can use sudo, set up as in Set up a fresh Ubuntu 24.04 server safely.
  • A password for the application's database user, kept in the shell variable APP_PASSWORD while you follow the steps: APP_PASSWORD=$(openssl rand -base64 24) makes a good one. Copy it into your application's settings with echo "$APP_PASSWORD", and run every step in the same terminal.
  • The guide names the user appuser and the database appdb. Use your own names, the same in every step.

Steps

1. Install PostgreSQL

Ubuntu 24.04 carries PostgreSQL 16 in its own archive, with security updates from Ubuntu.

sudo apt update
sudo apt install -y postgresql
sudo -u postgres psql -tAc 'SHOW server_version'
pg_lsclusters

The version starts with 16., and pg_lsclusters lists one cluster, 16 main, with status online. Out of the box it listens only on the server itself (127.0.0.1 and ::1), so nothing outside can reach it.

2. Create the application's user and database

The application gets a role that can sign in and nothing more, a database it owns, and a limit of 20 connections. The REVOKE stops every other role from connecting to this database. psql puts the password in with :'pw', quoted as a string, so it never appears in the command.

sudo -u postgres psql -v ON_ERROR_STOP=1 -v pw="$APP_PASSWORD" <<'EOF'
CREATE ROLE appuser LOGIN PASSWORD :'pw' CONNECTION LIMIT 20;
CREATE DATABASE appdb OWNER appuser;
REVOKE CONNECT ON DATABASE appdb FROM PUBLIC;
EOF
sudo -u postgres psql -tAc "SELECT rolname, rolconnlimit, rolsuper, rolcreatedb FROM pg_roles WHERE rolname = 'appuser'"

The last line reads appuser|20|f|f: the role can hold 20 connections, is not a superuser and cannot create databases.

3. Connect as the application does

Applications connect over TCP to 127.0.0.1 with a password. The PostgreSQL client libraries, including node-postgres and psycopg, read the same PG* variables as psql, so these four settings are all most applications need.

export PGHOST=127.0.0.1 PGPORT=5432 PGUSER=appuser PGDATABASE=appdb
export PGPASSWORD="$APP_PASSWORD"
psql -tAc "SELECT current_user, current_database(), inet_server_addr()"
psql -v ON_ERROR_STOP=1 -c "CREATE TABLE notes (id serial PRIMARY KEY, body text NOT NULL)" -c "INSERT INTO notes (body) SELECT 'note ' || n FROM generate_series(1, 1000) AS n"
unset PGPASSWORD

The first query prints appuser|appdb|127.0.0.1. The second makes a table and fills it with 1,000 rows, which the backup check uses later. In your application, keep the password in its environment file, readable only by the service, never in the code.

4. Back the database up every night

pg_dump writes a consistent copy of one database while the application keeps running. The custom format (-Fc) is compressed and lets you restore one table at a time. A systemd timer runs it at 03:15 each night and keeps 14 days of files.

sudo install -d -m 700 -o postgres -g postgres /var/backups/postgresql
sudo tee /etc/systemd/system/appdb-backup.service > /dev/null <<'EOF'
[Unit]
Description=Back up the appdb database

[Service]
Type=oneshot
User=postgres
ExecStart=/bin/sh -c 'pg_dump -Fc -f /var/backups/postgresql/appdb-$(date -u +%%Y%%m%%dT%%H%%M%%SZ).dump appdb'
ExecStartPost=/usr/bin/find /var/backups/postgresql -name 'appdb-*.dump' -mtime +14 -delete
EOF
sudo tee /etc/systemd/system/appdb-backup.timer > /dev/null <<'EOF'
[Unit]
Description=Back up the appdb database every night

[Timer]
OnCalendar=*-*-* 03:15:00
Persistent=true

[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now appdb-backup.timer
systemctl list-timers appdb-backup.timer --no-pager

list-timers shows the next run at 03:15. Persistent=true means a run missed while the server was off happens when it starts again.

5. Take one backup now and restore it

A backup you have never restored is a hope, not a backup. Run the service once, restore the newest file into a scratch database, and count the rows.

sudo systemctl start appdb-backup.service
sudo ls -l /var/backups/postgresql
latest=$(sudo ls -1t /var/backups/postgresql | head -n 1)
sudo -u postgres createdb appdb_restore_test
sudo -u postgres pg_restore --no-owner -d appdb_restore_test "/var/backups/postgresql/$latest"
sudo -u postgres psql -d appdb_restore_test -tAc 'SELECT count(*) FROM notes'
sudo -u postgres dropdb appdb_restore_test

ls lists one file named like appdb-20261027T031500Z.dump, and the count prints 1000: every row came back.

Check that it works

Ask PostgreSQL for the role's limit and who is connected, and check the backup timer is waiting for its next run:

sudo -u postgres psql -tAc "SELECT rolconnlimit FROM pg_roles WHERE rolname = 'appuser'"
sudo -u postgres psql -tAc "SELECT count(*) FROM pg_stat_activity WHERE usename = 'appuser'"
systemctl is-enabled appdb-backup.timer

The lines read 20, the number of connections your application holds right now, and enabled.

What can go wrong

  • psql answers Peer authentication failed for user "appuser". It connected through the local socket, where PostgreSQL on Ubuntu checks the operating system user's name instead of a password. Connect over TCP: set PGHOST=127.0.0.1, or pass -h 127.0.0.1.
  • The application logs FATAL: password authentication failed for user "appuser". The password differs from the one in step 2. Set it again with sudo -u postgres psql -c "ALTER ROLE appuser PASSWORD 'NEW_PASSWORD'" and update the application's environment.
  • The application logs FATAL: too many connections for role "appuser". It opened more than 20 connections. Lower its pool size (max in node-postgres) below the limit, or raise the limit with ALTER ROLE appuser CONNECTION LIMIT 40, keeping the total for every role under SHOW max_connections (100 by default).
  • The backup service fails. sudo journalctl -u appdb-backup.service -n 20 shows why. A full disk is the usual cause: df -h /var/backups tells you, and the files older than 14 days are deleted only after a backup succeeds.
  • The application runs on another server and cannot connect. PostgreSQL listens on the server itself only. Set listen_addresses in /etc/postgresql/16/main/postgresql.conf, add one host appdb appuser PRIVATE_NETWORK_RANGE scram-sha-256 line to /etc/postgresql/16/main/pg_hba.conf, restart PostgreSQL, and allow port 5432 from that range only in the firewall. Never open it to the internet.

Good practice

  • One role and one database per application, never the postgres superuser in an application's settings.
  • Keep the connection limit just above the application's pool size, so a leak shows as an error instead of taking every connection on the server.
  • Copy the backup files off the server too. A backup on the same disk does not survive the disk.
  • Restore a backup into a scratch database on a schedule, not only once. The restore is the test.
  • Keep PostgreSQL updated through apt; minor versions fix bugs and security issues without changing your data.

Where to go next

  • Set up a fresh Ubuntu 24.04 server safely
  • Run a Next.js app as a systemd service on Ubuntu
  • Firewall Configuration

Related Articles

Tune Valkey, Qdrant, Meilisearch, and MinIO cleanly

Read more

Frequently Asked Questions

What does the Set up PostgreSQL for a web app on Ubuntu 24.04 documentation guide cover?
Give an application its own PostgreSQL user and database with a connection limit, connect to it, and back it up nightly with a restore you have tested. It is rated intermediate difficulty (25 min) and applies to Servers Are Up infrastructure and workflows.
Can I manage or automate these steps through the Servers Are Up dashboard, REST API v1, or MCP server?
Yes. Every Servers Are Up server includes browser-based SSH, WebRDP, and VNC console access in the dashboard, plus programmatic control via the REST API v1 (/api/v1) and hosted Model Context Protocol server (/api/mcp/v1) using a scoped Personal Access Token.

Need hands-on help with Set up PostgreSQL for a web app on Ubuntu 24.04?

Every Servers Are Up virtual machine and container includes an integrated HTML5 browser-based SSH, RDP, and VNC console in your dashboard, default-off inbound firewall rules with per-IP allow-lists, and full programmatic control via REST API v1 and Model Context Protocol (MCP). Explore our Virtual Datacenter Plans or reach out to Servers Are Up Support.

Was this article helpful?

On this page

What you will have at the endBefore you startSteps1. Install PostgreSQL2. Create the application's user and database3. Connect as the application does4. Back the database up every night5. Take one backup now and restore itCheck that it worksWhat can go wrongGood practiceWhere to go next
Need Live Commands?

Open Aria in Wide Engineering Mode for distro-specific commands, compose tweaks, and isolated environment troubleshooting.

Knowledge Library