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
VGSources
Blog

How to Create a PostgreSQL Database on a Linux VPS

A practical Ubuntu VPS guide to installing PostgreSQL, creating an application role and database, testing socket and TCP connections, configuring secure remote access, troubleshooting authentication, and planning backups.
Length12 min Posted Quest giverVGSources Team

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.

To create a PostgreSQL database on an Ubuntu Linux VPS, install the PostgreSQL package, create a password-authenticated application role, create a database owned by that role, and test the connection locally before opening any remote access. Remote connections require three settings to agree: PostgreSQL must listen on the required interface, the VPS firewall must allow TCP port 5432 only from approved addresses, and a matching pg_hba.conf rule must authenticate the client.

The commands below use Ubuntu’s package layout and defaults. They keep the PostgreSQL superuser for administration, use SCRAM password authentication for network connections, and avoid exposing the database to the public Internet unnecessarily.

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

You need an Ubuntu VPS with sudo access, a hostname or IP address for the server, and a clear decision about which machines should connect. The examples use these names:

  • appuser — the dedicated login role for the application.
  • appdb — the database owned by that role.
  • server-address — the VPS hostname or IP address.
  • application-ip — the fixed public IP address of the application server or administrator workstation, if remote access is required.

Replace those example values before running commands. Do not use the PostgreSQL superuser for an application connection. A dedicated owner limits the damage caused by a leaked application credential and makes ownership and rotation easier to manage.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Install PostgreSQL and confirm that it is running

Install the Ubuntu package

Update the package index and install PostgreSQL with Ubuntu’s supported package:

sudo apt update
sudo apt install postgresql

The package creates and starts a PostgreSQL service with usable defaults. Installing the package does not create your application role or application database; those are separate steps.

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

Check the service

sudo systemctl status postgresql

Look for active (exited) or an active PostgreSQL cluster reported by the service manager. On Ubuntu, the service is commonly managed through the postgresql unit even though the actual cluster has its own versioned process. If it is not running, start it and configure it to start at boot:

sudo systemctl start postgresql
sudo systemctl enable postgresql

For a more direct check, ask PostgreSQL whether it is accepting connections:

sudo -u postgres pg_isready

A response indicating that the server is accepting connections confirms that the database engine is reachable through its local socket. The main configuration directory is normally /etc/postgresql/<version>/main/, where <version> is the installed major version. The exact directory can be confirmed from SQL:

sudo -u postgres psql -c 'SHOW config_file;'
sudo -u postgres psql -c 'SHOW hba_file;'

Keep the reported paths handy. Editing a different version’s configuration is a common reason for changes appearing to have no effect.

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

Create a dedicated PostgreSQL role

Create the role from psql

Ubuntu gives the operating-system account named postgres administrative access to the local server. Open the PostgreSQL command-line client as that account:

sudo -u postgres psql

Inside psql, create a login role with a password:

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

Exit with q. Use a password generated for this role only; do not reuse the VPS login password. PostgreSQL stores a verifier rather than the clear-text password when SCRAM is used, but anyone who can read an application’s configuration may still be able to use its credentials, so protect environment files and secrets.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

You can also let PostgreSQL prompt for the password without placing it in shell history:

sudo -u postgres createuser --pwprompt appuser

The createuser command creates a role; the --pwprompt option asks for a password interactively. It does not create a database.

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

Verify role attributes

sudo -u postgres psql -c 'du appuser'

Confirm that the role has the Login attribute and does not have unnecessary attributes such as superuser, role-creation, database-creation, or replication privileges. If an application needs a narrowly defined privilege later, grant only that privilege on the required objects.

Create the database and assign ownership

Use SQL when you want explicit control

Open psql as the administrator and run:

sudo -u postgres psql
CREATE DATABASE appdb OWNER appuser;

The server must be running, and the executing role must have permission to create databases. Creating a database for another role is privilege-controlled. The OWNER appuser clause makes the application role the database owner instead of leaving ownership with postgres.

Check the result from the shell:

sudo -u postgres psql -lqt | grep appdb

Use createdb for a concise script

The equivalent shell command is:

sudo -u postgres createdb -O appuser appdb

createdb is convenient in deployment scripts. SQL is more expressive when you need to set encoding, locale, templates, or additional grants in the same administrative session.

Method Best use Ownership expression Operational note
CREATE DATABASE Interactive administration or migrations that need several SQL statements Explicit in the statement with OWNER appuser Easy to extend with database options and follow-up grants
createdb -O appuser appdb Short shell scripts and provisioning steps Explicit through the -O option Requires a running server and suitable administrative privileges

Creating the database does not automatically create application tables, schemas, extensions, or least-privilege grants. Those belong in your application migration process.

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

Test the database locally before enabling remote access

Test a TCP connection with a password

Run this on the VPS:

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

The -h localhost option deliberately uses TCP instead of the default Unix-domain socket. The -W option prompts for the role password. Once connected, verify the identity and database:

SELECT current_user, current_database(), inet_server_addr(), inet_server_port();

Exit with q. This test exercises the host authentication rule and proves that the role, password, database, and local TCP listener agree.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Understand socket versus TCP authentication

Connection form Example Typical Ubuntu authentication What it tests
Unix socket psql -d appdb -U appuser peer by default for local connections Whether the operating-system user maps to the PostgreSQL role
TCP loopback psql -d appdb -U appuser -h localhost -W scram-sha-256 by default for host connections in current Ubuntu releases Whether password authentication and the local TCP listener work

With peer, PostgreSQL compares the operating-system account to the requested database role. Running psql -U appuser while logged into Linux as a different account can therefore fail even when the password is correct. Use -h localhost for a password-based test, or connect as the matching operating-system account when a socket connection is intentional.

Ubuntu documents peer as the default for local connections and scram-sha-256 as the default for host connections in current releases; older Ubuntu versions used md5 for host connections. Always inspect the active pg_hba.conf rather than assuming a distribution default.

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

Enable remote access only when it is required

A local-only database is safer and simpler. If the application runs on another machine, configure all three layers: PostgreSQL’s listening address, the VPS or cloud firewall, and a matching host rule in pg_hba.conf. Changing only one layer cannot make a secure remote connection work.

Set a specific listening address

Find the active configuration file with:

sudo -u postgres psql -c 'SHOW config_file;'

Edit that file as root and set listen_addresses to the interface or addresses that must accept connections. For a server with a single private interface, use its private address when possible. To listen on all interfaces, the value would be *, but that increases exposure and should not be the default choice.

sudoedit /etc/postgresql/<version>/main/postgresql.conf
listen_addresses = '10.0.0.10'

Use the actual VPS address, and ensure that address remains stable. A setting of localhost permits only local connections.

Add the narrowest pg_hba.conf rule

Locate the active host-based authentication file:

sudo -u postgres psql -c 'SHOW hba_file;'

Add a rule that names the database, role, and source address. A single fixed application host could use:

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

For a private subnet, use the smallest subnet that contains the application hosts, such as 10.0.2.0/24, rather than allowing every IPv4 address. If TLS is configured with a certificate trusted by clients, use hostssl instead:

hostssl appdb    appuser    application-ip/32    scram-sha-256

Ubuntu’s guidance uses hostssl for encrypted connections and notes that a trusted certificate authority is appropriate for production. A hostssl rule does not by itself create certificates or force a client to validate the server identity; configure certificate validation in the client as part of your TLS deployment.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Restrict TCP port 5432 at the firewall

Allow the PostgreSQL port only from the application server or an administrator address. The exact command depends on the firewall, cloud security group, and hosting network. The policy should be equivalent to “permit TCP 5432 from application-ip; deny other sources.” Do not open 5432 to 0.0.0.0/0 merely to make testing convenient.

Check both the VPS firewall and any provider-level security group. A provider rule that blocks the port will look like a PostgreSQL failure even when the local configuration is correct.

Reload configuration and test remotely

After saving both files, reload PostgreSQL:

sudo systemctl reload postgresql

A reload applies settings that support reloads, including host-based authentication changes. If a listening-address change is not applied by reload on your installation, restart the service during an approved maintenance window:

sudo systemctl restart postgresql

From an approved client, test with:

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

If the test succeeds, confirm that the client is using TLS when required. PostgreSQL client options and connection strings can enforce certificate verification; do not treat a successful password login as proof that encryption or server identity validation is enabled.

How pg_hba.conf matching really works

PostgreSQL evaluates pg_hba.conf from top to bottom. It chooses the first record matching the connection type, client address, database, and user. There is no fall-through after an authentication failure: if the selected record rejects the password, PostgreSQL does not try a later, more permissive record.

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.

Place specific rules above broad rules. For example, put the appdb/appuser rule for the application address before a general rule for the subnet. After editing, inspect the effective file carefully for earlier records that match the same connection.

Never use trust on an Internet-facing VPS. The upstream PostgreSQL documentation warns that trust allows anyone who can reach the server to log in as any PostgreSQL user without a password. It may be acceptable for a tightly isolated temporary test network, but it is not an appropriate production authentication method.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot the most common failures

“Peer authentication failed for user”

  • You connected through a Unix socket, so the local rule selected peer.
  • Your Linux account name does not match appuser.
  • The active pg_hba.conf contains an earlier local rule than the one you edited.

For a password test, run psql -d appdb -U appuser -h localhost -W. If you intentionally want socket authentication, connect as the matching operating-system account or create an explicit, carefully scoped mapping rather than weakening authentication globally.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

“Connection refused”

  • The PostgreSQL service is stopped; check sudo systemctl status postgresql.
  • listen_addresses does not include the address being used.
  • The firewall or cloud security group blocks TCP 5432.
  • The client is targeting the wrong address or port.

Use sudo -u postgres pg_isready locally, then check the listening sockets with the operating system’s network tools. A refusal usually means no process is listening or a firewall is actively rejecting the connection; it is different from an authentication error.

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

“No pg_hba.conf entry”

The server is reachable, but no rule matches the client’s connection type, source address, database, and role. Add the narrowest matching host or hostssl record, place it before broader records, and reload PostgreSQL. Check whether the client is arriving over IPv4 or IPv6; an IPv4 rule does not match an IPv6 source.

“Password authentication failed”

  • The password was entered incorrectly or belongs to another role.
  • The client reached a different PostgreSQL instance than the one you configured.
  • The role lacks the LOGIN attribute.
  • An earlier pg_hba.conf record selected a different authentication method.

Reset the role password as the administrator, then retest locally over TCP before testing from the remote host:

sudo -u postgres psql -c "ALTER ROLE appuser PASSWORD 'new-long-random-password';"

Protect shell history when using password-bearing commands; an interactive psql session or password prompt is safer.

“Database does not exist” or ownership errors

List databases and owners:

sudo -u postgres psql -l

If appdb is missing, create it with CREATE DATABASE appdb OWNER appuser; or createdb -O appuser appdb. If the database exists but is owned by the wrong role, change ownership deliberately:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo -u postgres psql -c 'ALTER DATABASE appdb OWNER TO appuser;'

Changing ownership does not automatically grant access to every object created by another role; review schema and object privileges separately.

Back up the database and verify recovery

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 so a disk failure, compromised host, or accidental deletion does not destroy both the live database and its backup.

Logical backup of one database

pg_dump --format=custom --file=appdb.dump --dbname=appdb --username=appuser --host=localhost

The custom format supports selective restoration and is convenient for a single database. Schedule it with a service account or backup system that can authenticate without exposing a password in process listings.

Logical backup of roles and all databases

pg_dumpall --globals-only > globals.sql
pg_dumpall --database=postgres > cluster.sql

pg_dumpall --globals-only captures cluster-wide roles and tablespaces. A per-database pg_dump is often easier to restore selectively, while a full logical dump can be useful for a small VPS when you need a complete cluster export.

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

Choose a backup strategy that matches recovery needs

Approach Restore granularity Recovery characteristics Operational overhead
Logical dump such as pg_dump Database, schema, table, or selected objects Portable and useful for migrations; restore time depends on dump size Simple to automate, but requires regular dump jobs and restore tests
Physical backup Cluster or server data directory Suitable for larger databases and tighter recovery objectives when implemented correctly Requires PostgreSQL-aware procedures, storage planning, and careful consistency checks
Managed or provider backup Depends on the service’s snapshot and export features May simplify point-in-time or infrastructure recovery, but terms and retention vary Less local maintenance, with dependence on the provider’s controls and restore process

At least once, restore a backup into a separate test cluster or temporary VPS, verify that the application can read and write expected data, and record the time required. The correct method depends on database size, acceptable data loss, recovery time, and how much administration your team can perform.

Security checklist for a production VPS

  • Keep the application on a dedicated login role; reserve postgres for administration.
  • Use a long, unique password and store it in a secret manager or protected environment file.
  • Keep PostgreSQL local-only unless another machine genuinely needs access.
  • Bind listen_addresses to the required interface instead of using * by default.
  • Allow TCP 5432 only from approved application or administrator addresses at every firewall layer.
  • Use scram-sha-256 for password authentication and prefer hostssl with certificate validation for remote production traffic.
  • Review pg_hba.conf from top to bottom because the first matching record wins.
  • Never deploy trust authentication on an Internet-facing server.
  • Apply security updates and monitor PostgreSQL logs for failed authentication and unexpected source addresses.
  • Automate backups, keep copies off the VPS, and test restoration on a schedule.

End-to-end provisioning sequence

For a repeatable setup, use this order:

  1. Install PostgreSQL with sudo apt install postgresql.
  2. Confirm the service and active configuration paths with systemctl, pg_isready, and SHOW config_file.
  3. Create appuser with LOGIN and a unique password.
  4. Create appdb with appuser as owner.
  5. Test psql -d appdb -U appuser -h localhost -W on the VPS.
  6. If remote access is required, set a specific listen_addresses value, add a narrow host or hostssl rule, and restrict port 5432 at the firewall.
  7. Reload or restart PostgreSQL, then test from the approved client with the server address.
  8. Configure recurring backups, copy them off-host, and perform a documented restore test.

This sequence isolates local PostgreSQL problems from network problems and ensures that database ownership, authentication, exposure, and recovery are addressed before the application is connected.

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.

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.