Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween 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 Encrypt a PostgreSQL Database at Rest on Ubuntu

Use LUKS/dm-crypt to protect PostgreSQL's entire Ubuntu storage boundary, then add pgcrypto only for selected fields that need ciphertext while the database is online. This guide covers migration, startup ordering, TPM and passphrase unlocks, backups, threat limits, and recovery testing.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For whole-cluster at-rest encryption on Ubuntu, put PostgreSQL’s data storage on a LUKS volume backed by Linux dm-crypt. Unlock and mount that volume before PostgreSQL starts, and include every tablespace, WAL location, replica, snapshot, dump, and backup that must receive the same protection. Use PostgreSQL’s pgcrypto module only for selected values that must remain ciphertext while the database is online; it does not replace volume encryption.

What at-rest encryption protects

At-rest encryption protects storage when the storage device is locked, powered off, removed, or stolen. Ubuntu describes full-disk encryption as ensuring that data on an entire disk or selected partitions is encrypted at rest, using the Linux Unified Key Setup (LUKS) framework at the block level. PostgreSQL’s encryption documentation identifies dm-crypt plus LUKS as the Linux block-level or full-disk option for preventing unencrypted data from being read after a drive or computer is stolen.

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.

The important boundary is the unlock event. Once the LUKS mapping is opened and its filesystem is mounted, the operating system presents normal, readable files to PostgreSQL. A database process, a root-level attacker, or a privileged administrator on that running host can therefore access data according to the permissions and controls on the live system. LUKS is protection for storage that is not currently available to the operating system, not encryption of every query result or memory page.

The recommended Ubuntu architecture

Use a separate encrypted block device or partition for the PostgreSQL storage that needs protection. The usual flow is:

#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.
  1. Ubuntu opens the LUKS container, creating a dm-crypt mapping.
  2. The operating system mounts the filesystem on that mapping.
  3. Ownership, permissions, and mandatory-access-control policy are checked for the PostgreSQL service account.
  4. Only after the mount is available does the PostgreSQL service start.

The encrypted scope must follow the data, not merely the directory name. A cluster can use external tablespaces, a separately located WAL directory, replica storage, or temporary staging paths. Any one of those left on an unencrypted device can create an unprotected copy of information that the primary data directory does not contain.

Plan the threat model before changing storage

Write down what “encrypted at rest” means for this deployment. A requirement covering only the primary cluster is different from one covering every copy of the data. Decide whether the following are in scope:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • the main PostgreSQL data directory;
  • WAL files and an archive destination;
  • tablespaces outside the main directory;
  • logical dumps, physical backups, and backup catalogs;
  • replicas, standby servers, and their disks;
  • cloud-volume snapshots and exported images;
  • temporary files or staging exports created by maintenance jobs.

Also define who may unlock the volume, whether a human must be present during boot, where recovery material is stored, and what happens if the primary key, TPM, or host is lost. A design that encrypts the disk but has no tested recovery path is not a complete database protection plan.

Inventory the PostgreSQL paths

Do this inventory before creating or moving any encrypted volume. On Ubuntu, run read-only queries as the PostgreSQL operating-system account to identify the active cluster location and tablespaces:

  • sudo -u postgres psql -Atc 'SHOW data_directory;' reports the active data directory.
  • sudo -u postgres psql -Atc 'SELECT spcname, pg_tablespace_location(oid) FROM pg_tablespace;' lists tablespaces and their filesystem locations. An empty location denotes the default tablespace inside the cluster directory.

Inspect the resulting paths on the host. Confirm whether pg_wal is inside the cluster or has been placed elsewhere, and identify the destinations used by backup, archiving, export, and snapshot jobs. Check for symbolic links and mounts so that an apparently local path is not silently crossing onto another device. Record filesystem identifiers rather than relying on a device name that can change between boots.

Prepare the encrypted storage

Fresh Ubuntu installation

For a new host, create the encrypted storage during installation or with Ubuntu’s supported storage tooling. Put the filesystem that will contain the cluster on the LUKS-backed mapping, and decide separately whether the operating-system volume, swap, and other service data require encryption. Keep the PostgreSQL service disabled until the encrypted mount has been created, populated, and verified.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

The exact partition layout depends on whether the machine uses a single disk, separate data disks, RAID, or a cloud volume. Do not copy a layout intended for one of those environments to another without checking boot behavior, recovery access, and the provider’s snapshot model.

Existing cluster

Do not format or reinitialize a live PostgreSQL data device in place. A safe migration needs a maintenance window or a replication-based cutover:

  1. Take a backup whose restore procedure is already understood, and verify that it is readable before touching the source.
  2. Create the LUKS-backed filesystem on new storage. The new filesystem must not be mounted over the old directory until the copy has been validated.
  3. Stop writes using a planned outage, or synchronize a replacement host and promote it according to the replication plan.
  4. Copy or restore the cluster, tablespaces, and required WAL according to the chosen migration method.
  5. Mount the encrypted filesystem at the final path, preserve PostgreSQL ownership and directory permissions, and check AppArmor or SELinux policy where those controls are enabled.
  6. Start PostgreSQL against the new location, run consistency and application checks, and retain the old copy only until the rollback and validation period has ended.
  7. After confirming that no unencrypted copy is required, remove or securely dispose of the old storage under the organization’s retention policy.

The migration method and service settings differ for a package-managed cluster, a manually initialized cluster, and a cloud virtual machine. Treat the storage move, service ordering, and rollback as one change rather than changing only data_directory.

Make unlock, mount, and service startup one operation

PostgreSQL must never start while its intended encrypted filesystem is absent. If the mount fails and the service starts anyway, it could write into an ordinary directory on the root filesystem, creating an unencrypted second cluster or masking the real data. Configure the boot and service dependencies so that opening the LUKS mapping and mounting the filesystem are prerequisites for PostgreSQL startup, and so a failed mount prevents the service from proceeding.

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.

At every boot or service restart, verify:

  • the expected LUKS mapping is open;
  • the expected filesystem identifier is mounted at the expected path;
  • the mount is writable by PostgreSQL and not by unintended users;
  • mandatory-access-control rules still permit PostgreSQL to read and write the path;
  • the service is using that path, not a fallback directory.

After a successful start, confirm the active data_directory from SQL and compare it with the mounted filesystem. Include this check in monitoring or the startup runbook rather than relying on visual inspection during an incident.

Choose how the LUKS volume unlocks

Operator-entered passphrase

A passphrase is straightforward and keeps unattended boot from automatically exposing the database volume. Someone must supply it at boot or service start, which can be appropriate for a server whose operator is expected to be present. Store an offline recovery method separately from the host and document who is authorized to use it.

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)

LUKS stores the volume key in encrypted form in its header and derives a key-encryption key from the passphrase. Ubuntu documents PBKDF2 for LUKS1 and Argon2 for LUKS2. The passphrase protects access to the volume; it is not a PostgreSQL role password and should not be placed in database configuration files or an unencrypted script.

TPM-assisted unlocking with Clevis

Ubuntu also documents TPM-backed unlock paths, including integration with Clevis. This can allow a trusted machine to unlock automatically when the expected measured-boot conditions are present. The trade-off is operational: boot measurements, TPM availability, enrollment, firmware changes, and recovery-key procedures all become dependencies.

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

Use a TPM path only with a tested fallback. Keep an offline recovery key, document how to re-enroll after motherboard or firmware replacement, and define what happens when the host no longer satisfies the policy. Automatic boot is convenient, but it does not remove the need for key custody, revocation, or incident response.

Include copies outside the primary data directory

WAL and tablespaces

WAL can contain row changes and values that are not yet represented in a backup. If it is on a separate device, encrypt that device as well. External tablespaces must be checked individually; encrypting the main cluster path does not encrypt a tablespace mounted elsewhere.

Backups, dumps, and snapshots

A database volume can be encrypted while an exported dump remains an ordinary readable file. Encrypt backup destinations and the media or object storage that holds them. Apply the same rule to replica disks and to snapshots or machine images: a snapshot created outside the encrypted boundary may expose the database even when the live volume is protected.

Document which key is needed for each backup set, how retention and deletion work, and how a restore is performed on a clean host. Test the restore, not just the backup job’s success message.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

LUKS versus pgcrypto

These mechanisms solve different problems and are often used together.

Decision axis LUKS with dm-crypt PostgreSQL pgcrypto
Coverage Whole encrypted block device or partition, covering the filesystem placed there. Selected columns or values that the application explicitly encrypts.
Protected state Data on a locked, removed, or powered-off device. Chosen values remain ciphertext in storage while other database data is unchanged.
Plaintext exposure After the mapping is opened and the filesystem is mounted, the operating system provides normal plaintext files. Plaintext and keys exist during database processing and when encrypted values are decrypted for a query.
Key and boot behavior Passphrase entry or TPM-assisted unlock, plus recovery material. Keys must be supplied by the application or a separate key-management process; database access alone must not expose them unnecessarily.
Operational scope Requires coverage decisions for WAL, tablespaces, backups, replicas, and snapshots. Requires application changes, key lifecycle design, and careful handling of encrypted and decrypted values.
Primary failure mode An unavailable key, TPM, or mount prevents the database from starting. Lost application keys can make selected values unrecoverable; incorrect encryption handling can also break queries or migrations.

Use pgcrypto for selected fields, not as disk encryption

The pgcrypto extension provides hashing, password hashing, PGP encryption, and raw encryption functions. PostgreSQL requires the server to have OpenSSL support for the module. It is appropriate when the application needs a particular identifier, note, token, or other field stored as ciphertext even after the database volume is online.

Encryption must be designed into the data model. Decide which columns are encrypted, how keys are selected and rotated, whether equality search or ordering is still required, and how old ciphertext is re-encrypted during a key change. Keep application or key-service credentials outside the database data directory and restrict which services can request decryption.

PostgreSQL cautions that all pgcrypto functions run inside the database server. Values and passwords can move in clear text between pgcrypto and client applications, so use local connections or SSL/TLS connections. If the server and its database administrators cannot be trusted, perform the cryptography in the client application or another trusted service instead. Field encryption does not hide plaintext from a compromised running server that can execute the decryption operation.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What LUKS does not defend against

Because a mounted filesystem provides an unencrypted view, LUKS alone does not protect against a compromised running host, a malicious root user, an attacker who has taken over PostgreSQL, or an administrator who already has permission to read the files. It also does not encrypt network traffic, database authentication, query results, logs, or backups placed outside the encrypted boundary.

Pair storage encryption with least-privilege PostgreSQL roles, strong authentication, TLS for client connections, host patching and hardening, restricted administrative access, encrypted backups, and monitoring. These controls address different stages of the attack and should not be presented as interchangeable.

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.

Performance and hardware decisions

No universal overhead percentage or hardware recommendation is established for this Ubuntu/PostgreSQL arrangement. Encryption cost depends on the CPU, storage device, workload, filesystem, WAL rate, concurrency, and whether other services share the host. Measure the actual system rather than selecting hardware from a generic claim.

Benchmark a representative workload before production migration, measuring transaction latency, throughput, checkpoint behavior, WAL generation, backup duration, restart time, and recovery time with the encrypted layout. Repeat the test after enabling any field-level encryption because database-side cryptography changes CPU use and query behavior differently from block encryption. Keep the test conditions and dataset size so that a later hardware or PostgreSQL change can be compared fairly.

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

Recovery and operational checklist

  • Record the encrypted devices, filesystem identifiers, mount points, tablespaces, WAL location, and backup destinations.
  • Identify the people or systems authorized to unlock each volume.
  • Store offline recovery material separately from the server and test that it works.
  • Document the boot sequence: unlock, mount, permission checks, policy checks, PostgreSQL start, and verification.
  • Encrypt replicas, dumps, snapshots, and backup media independently where they are stored.
  • Test a clean-host restore, including the key required to read each backup.
  • Exercise the lost-passphrase and failed-TPM procedures in a non-production environment.
  • Plan key rotation or revocation without leaving an old unencrypted copy behind.
  • Monitor for an absent mount, an unexpected filesystem at the data path, or PostgreSQL starting before the encrypted volume is ready.

Troubleshooting common failures

PostgreSQL starts but the encrypted volume is not mounted

Stop the service before it writes more data. Check the mounted filesystem and the service’s active data directory, then correct the startup dependency so a missing mount causes a hard failure. Inspect whether PostgreSQL created a new empty directory beneath the intended mount point; that directory must not be mistaken for the real cluster.

The volume will not unlock

Do not repeatedly overwrite the LUKS header or reinitialize the device. Confirm that the correct passphrase or recovery key is being used, and for TPM-assisted unlocking check the TPM’s availability and the measured-boot conditions. If the original key material is unavailable, recovery depends on a separate backup or a tested replica; LUKS does not provide a back door.

PostgreSQL cannot read the mounted path

Verify ownership, mode bits, mount options, symbolic links, and AppArmor or SELinux policy. Compare the path used by PostgreSQL with the path that was mounted, and check that every external tablespace is available before starting the cluster.

A restore succeeds but some data is missing

Check whether WAL archives, external tablespaces, or a separately stored backup catalog were omitted from the encrypted backup set. A protected primary directory is not proof that all recovery inputs were protected or retained.

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

Choosing the right design

  • Need protection from a stolen or removed Ubuntu disk: use LUKS and dm-crypt for the complete storage boundary, including every required copy.
  • Need only a few sensitive fields hidden while the database remains online: add pgcrypto or application-side encryption with a separate key-management design.
  • Need both properties: encrypt the storage with LUKS and encrypt especially sensitive fields separately, accepting the additional key and application complexity.
  • Need protection from a compromised running host: do not treat LUKS as sufficient; strengthen host, database, network, role, and monitoring controls, and consider client-side cryptography for data that the server must not see.

The practical test is not whether a LUKS header exists. It is whether every relevant copy is covered, the volume cannot be bypassed during startup, authorized operators can recover it, and the design still limits exposure after the host is running.

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
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.