Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk9 min

How to Create a PostgreSQL Database on a Linux VPS

A practical Ubuntu VPS guide to installing PostgreSQL, creating an application role and database, fixing peer-authentication errors, safely enabling remote connections, and testing backups.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable sequence is: install PostgreSQL, create a dedicated login role, create a database owned by that role, test locally, and expose PostgreSQL remotely only if the application requires it. Remote access works only when PostgreSQL is listening on the right interface, the VPS firewall permits the client, and a matching pg_hba.conf rule allows that user and database.

The commands below assume an Ubuntu Linux VPS and a shell account with sudo access. Replace appuser, appdb, IP addresses, and passwords with values appropriate for your application.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What you need before starting

  • An Ubuntu VPS with administrative access through sudo.
  • A planned database name, application role name, and password.
  • The application server’s private or public IP address if another machine will connect.
  • A firewall policy that permits only the administrators and application hosts that need PostgreSQL.
  • A backup destination outside the VPS.

Do not use the built-in postgres superuser for an application. Keep that account for administration and create a separate login role with only the access the application needs.

Install PostgreSQL and confirm that it is running

Install the Ubuntu package

sudo apt update
sudo apt install postgresql

The Ubuntu package supplies a PostgreSQL service and a working default configuration. Installation alone does not create your application database or role. Those are separate administrative steps.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Check the service

sudo systemctl status postgresql
psql --version

The service should show as active. If it is not running, inspect the service output before attempting to create a database:

sudo systemctl start postgresql
sudo journalctl -u postgresql --no-pager -n 50

Ubuntu normally keeps the cluster configuration under /etc/postgresql/<version>/main/. The exact version directory depends on the package installed on your VPS. The files that matter for network access are usually postgresql.conf and pg_hba.conf.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create a dedicated PostgreSQL role

Use the PostgreSQL administrative account

On Ubuntu, the operating-system account named postgres can open the local administrative session:

sudo -u postgres psql

At the psql prompt, create a login role. A password entered directly in SQL can remain in shell history or process logs, so use a temporary example only, or set the password interactively with password.

CREATE ROLE appuser LOGIN PASSWORD 'replace-with-a-long-random-password';

A safer interactive pattern is:

sudo -u postgres psql
password appuser

If the role does not yet exist, create it first, then run password appuser. Exit with:

q

Use the documented command-line helper

Debian and Ubuntu also provide createuser. The password prompt avoids putting the password in the command itself:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo -u postgres createuser --pwprompt appuser

Do not add superuser, database-creation, or role-creation privileges unless your administration design explicitly requires them. An application normally needs to connect to its own database and perform its schema operations, not administer every database on the server.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Create the application database

SQL method

Reconnect as the PostgreSQL administrator and make the application role the owner:

sudo -u postgres psql
CREATE DATABASE appdb OWNER appuser;
q

CREATE DATABASE succeeds only while the PostgreSQL server is running and only for a role with the required privilege. Creating a database for another role is restricted; using the administrative account avoids accidentally assigning ownership to the wrong user.

Shell method

For scripts or one-off provisioning, use createdb:

sudo -u postgres createdb -O appuser appdb
Method Best use Ownership visibility Operational note
CREATE DATABASE appdb OWNER appuser; Manual administration, migrations, and scripts that already use psql Explicit in the SQL statement Returns a clear SQL error when the server or privileges are wrong
createdb -O appuser appdb Shell provisioning and automation Explicit through the -O option Requires the PostgreSQL server to be running and the invoking role to be authorized

Confirm the result from an administrative session:

sudo -u postgres psql -lqt

You should see appdb and its owner listed as appuser.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the database locally before enabling the network

Test a TCP connection with a password

Run this on the VPS:

psql -d appdb -U appuser -h localhost -W

-h localhost deliberately selects TCP instead of the local Unix socket. Enter the role password when prompted. A successful session proves that PostgreSQL is running, the database and role exist, and a host authentication rule accepts the combination.

Understand the peer-authentication error

Ubuntu uses peer by default for local socket connections and scram-sha-256 by default for host connections in current releases. Peer authentication compares the operating-system username with the requested PostgreSQL role. Therefore, this command can fail for a normal shell user:

psql -d appdb -U appuser

The command uses a socket, so PostgreSQL may require an operating-system account also named appuser. It does not mean the password is wrong. Use -h localhost -W for a password-based TCP test, or deliberately change the matching local rule only after considering the security implications.

Inspect the active authentication rules

From psql, you can locate the active configuration files:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
sudo -u postgres psql -c "SHOW config_file;"
sudo -u postgres psql -c "SHOW hba_file;"

Read the relevant local and host records in the reported pg_hba.conf. The record must match the connection type, client address, database, and user.

How pg_hba.conf decides whether a connection is allowed

PostgreSQL evaluates authentication records from top to bottom. The first record matching the connection type, source address, database, and user is selected. There is no fall-through: if that record’s authentication fails, PostgreSQL does not try a later record.

This ordering explains many confusing changes. A broad earlier local or host rule can intercept a connection before a narrower rule below it. Put a specific rule above a broader one, and remove obsolete entries rather than accumulating exceptions.

Common rule forms

# Local Unix-socket connections
local   appdb       appuser                         scram-sha-256

# TCP connections from one application server
host    appdb       appuser       203.0.113.10/32   scram-sha-256

# TLS-only connections from one application server
hostssl appdb       appuser       203.0.113.10/32   scram-sha-256

The address in the rule must be the source address PostgreSQL actually sees. If a load balancer, NAT gateway, or private network changes the source, use that observed address or range, not an assumed client address. A /32 entry permits one IPv4 address; use the smallest range that covers the real application hosts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Never use trust on an Internet-facing VPS

The trust method allows anyone who can reach the matching endpoint to log in as the PostgreSQL user without proving possession of a password. It is unsuitable for an Internet-facing server. Prefer scram-sha-256, and use TLS when traffic crosses an untrusted network.

Enable remote access only when the application needs it

A local-only database is safer and simpler. If the application runs on the same VPS, keep PostgreSQL bound to local interfaces and connect through a socket or localhost. Remote exposure adds three separate controls that must agree.

  1. PostgreSQL listening: the server must bind to the interface and port used by the client.
  2. Network firewall: the VPS provider firewall and the host firewall must permit TCP port 5432 only from approved sources.
  3. Authentication: pg_hba.conf must contain a matching rule for the database, role, and source address.

Set listen_addresses narrowly

Open the active postgresql.conf and set listen_addresses to the required private or public interface address. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
listen_addresses = '10.0.0.5'

Binding to a specific address is safer than using *, which listens on every available interface. If the application and database share the VPS, no non-local address is needed.

Restrict the firewall

Permit TCP 5432 only from the application server or a known administrator address. With UFW, a single-source rule can look like:

sudo ufw allow from 203.0.113.10 to any port 5432 proto tcp

Apply equivalent restrictions in any upstream VPS or cloud firewall. Do not open 5432 to the entire Internet merely to make testing easier. If you temporarily add a broad rule, remove it immediately after diagnosing the connection.

Add the narrowest host rule

Add a rule such as this to pg_hba.conf, above any broader conflicting rule:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
host appdb appuser 203.0.113.10/32 scram-sha-256

For encrypted connections, use hostssl instead:

hostssl appdb appuser 203.0.113.10/32 scram-sha-256

A production TLS deployment should use a certificate chain anchored by a trusted certificate authority. A hostssl record requires SSL negotiation; it does not by itself provide a trusted certificate or prove that the client is talking to the intended server.

Reload and test

After editing configuration, reload PostgreSQL so it rereads the files:

sudo systemctl reload postgresql

If a setting cannot be reloaded on your package or a configuration error prevents reload, inspect the service log and restart only during an appropriate maintenance window:

sudo systemctl restart postgresql

From the approved client, test with:

psql --host server-address --username appuser --dbname appdb --password

For a TLS-only rule, add the client options required by your certificate and verification policy rather than silently falling back to an unencrypted connection.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Local sockets versus TCP and remote connections

Connection type Typical command Security characteristics When to choose it
Local Unix socket psql -d appdb -U appuser No network exposure; commonly governed by peer authentication Administrative work or an application on the same VPS, when the local rule is designed for it
Local TCP psql -h localhost -d appdb -U appuser -W Uses host rules and password authentication; useful for isolating socket problems Testing password authentication or applications configured for TCP on the same machine
Remote TCP psql --host server-address --username appuser --dbname appdb --password Requires listening configuration, firewall access, and a matching host rule; encrypt with TLS when appropriate An application or administrator located on another machine

Give the application only the access it needs

Database ownership lets appuser manage objects in appdb, which is convenient for a small application. For a stricter deployment, use separate roles: one controlled migration role that can change the schema and one runtime role that can read and write only the required tables. Grant privileges explicitly and keep administrative roles out of application configuration.

Store the connection details in the application’s secret-management mechanism, not in a publicly readable file or source repository. A typical connection has four independent values: host, port (normally 5432), database name, and role name, plus the password or other authentication material.

Back up the database before relying on it

PostgreSQL databases should be backed up regularly. A backup that has never been restored is an assumption, not a recovery plan. Store copies away from the VPS and protect them with access controls and encryption appropriate to the data.

Logical backup of one database

pg_dump -Fc -d appdb -f appdb.dump

The custom-format dump is convenient for selective restoration with pg_restore. A basic restore into a newly created database is:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo -u postgres createdb -O appuser appdb_restore
pg_restore --clean --if-exists --dbname appdb_restore appdb.dump

Use a separate restore database for testing so that a recovery exercise cannot overwrite production data.

Save roles and other cluster-wide objects

A per-database dump does not replace a record of roles and global objects. Capture those separately:

sudo -u postgres pg_dumpall --globals-only > postgres-globals.sql

Choose a schedule based on how much data you can afford to lose. Keep enough historical copies to cover unnoticed corruption or accidental deletion, and periodically perform a complete restoration on a disposable system.

Logical versus physical or managed backups

Approach Restore granularity Recovery characteristics Operational overhead
Logical dumps such as pg_dump Database, schema, table, or selected objects Flexible but restore time grows with data volume Simple commands; you must schedule, copy, secure, and test them
Physical backup Cluster or server storage level Suitable for larger datasets and shorter recovery objectives when properly designed Requires PostgreSQL-aware procedures, storage management, and restore testing
Managed backup service Depends on the service’s snapshot and export features May reduce recovery work, but depends on the provider’s retention and recovery guarantees Less local administration; verify where copies are stored and how a full restore is performed

Troubleshoot the most common failures

Symptom Likely cause What to check
Peer authentication failed A socket connection matched a peer rule, but the operating-system user does not match the PostgreSQL role Retry with -h localhost -W; inspect the first matching local rule before changing it
password authentication failed Wrong password, wrong role, or a different first matching host rule than expected Reset the password as postgres, confirm the role has LOGIN, and review rule order
database does not exist The application database was never created or the client used a different name Run sudo -u postgres psql -lqt and verify spelling and ownership
connection refused PostgreSQL is stopped, not listening on the requested address, or the port is blocked Check systemctl status, listen_addresses, the configured port, and both firewall layers
Remote timeout A network firewall or routing rule drops the connection before PostgreSQL sees it Check the VPS firewall, upstream firewall, source IP, and whether the server is reachable on TCP 5432
A permissive rule appears ignored An earlier matching pg_hba.conf record was selected Move the specific rule above the broader one; authentication failures never fall through to later records
Reload fails A syntax error or setting that requires a restart Read the PostgreSQL service log, correct the file, then reload or restart during maintenance

A repeatable provisioning checklist

  1. Update package metadata and install PostgreSQL.
  2. Confirm the service is active and identify the configuration files.
  3. Create a dedicated login role and set a strong password interactively.
  4. Create appdb with that role as owner.
  5. Test psql -h localhost locally before changing network settings.
  6. Keep the database local-only unless a remote client is genuinely required.
  7. If remote access is needed, bind to the necessary interface, restrict firewalls, and add a narrow host or hostssl rule.
  8. Reload PostgreSQL and test from the actual client address.
  9. Record roles, configuration changes, and the recovery procedure.
  10. Schedule off-server backups and verify restoration regularly.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.