iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
The reliable way to connect a Python application on a VPS to PostgreSQL is to secure all four parts of the path: install Psycopg 3, create a dedicated database role, make PostgreSQL listen only where required, and permit that application network through a narrowly scoped firewall and pg_hba.conf rule. Use TLS with sslmode=verify-full, keep the password outside your repository, and set a finite connection timeout.
This guide shows the complete setup for a self-managed PostgreSQL server, using Ubuntu paths and service commands where the operating system documentation provides them. The same Python connection code also works when PostgreSQL is on a separate private host or managed service, provided the hostname, certificate, credentials, and network policy are correct.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWhat the connection path looks like
A Python process does not connect to PostgreSQL through the VPS operating system alone. A successful remote connection requires every layer below to agree:
- Python adapter: Psycopg 3 must be installed in the environment that runs your application.
- PostgreSQL listener: The server must listen on an address reachable from the application host, not only on its local loopback interface.
- Network path: DNS, routing, the VPS or cloud firewall, and the PostgreSQL port must allow traffic from the application source address.
- Host-based authentication: A matching
pg_hba.confrule must permit the source address, database, role, and authentication method. - Credentials and identity: The role password must be valid, and the requested database and role must exist.
- TLS: For a network connection, the client should encrypt traffic and verify that it is talking to the intended server.
If any one of these layers fails, Python reports only the resulting connection error. Troubleshooting is therefore fastest when you test the layers in that order rather than repeatedly changing the connection string.
#1 Best Overall
- Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
- With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
- Wide Application:Upgraded attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
- Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
- Warranty & Support: Our Electric air duster comes with 5 years warranty and 24/7 customer service. During this period, if you have any questions,pls kindly feel free to contact us.
Prepare the VPS and application prerequisites
Choose the topology first
In a simple deployment, both Python and PostgreSQL run on the same VPS. You can then keep PostgreSQL bound to a local interface and connect through the local socket or loopback address. If the application and database are on different machines, the database VPS must accept TCP connections from the application host or its private network.
Do not expose PostgreSQL broadly just because the application is remote. Identify the application server’s private address or source CIDR and use that value in the firewall and pg_hba.conf. If your provider supplies a private network, prefer it to a public interface.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesConfirm the software versions
Psycopg’s installation documentation publishes a support table for Python and PostgreSQL versions. Check that table before pinning a production deployment. The commands below use the current Psycopg 3 package and a virtual environment:
python -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install "psycopg[binary]"
The binary extra is the short installation path for supported systems. It supplies the client components needed for the common quick-start setup. For a repeatable deployment, record the resulting package version in your dependency lock or requirements file after confirming it against Psycopg’s support matrix.
Create a dedicated PostgreSQL role and database
Do not run the application as PostgreSQL’s superuser. A dedicated role limits the damage from an application bug or leaked credential and makes it possible to revoke the application independently of administrative accounts.
Connect to PostgreSQL using an administrative method that is already available on the server, then create an application role and database. Substitute your own names and a long, randomly generated password:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
CREATE ROLE app_user LOGIN PASSWORD 'replace-with-a-random-secret';
CREATE DATABASE app_db OWNER app_user;
Grant only the privileges the application needs. If the application must access an existing database instead of owning a new one, grant permissions on the required schema and tables rather than giving it superuser or broad administrative rights. Keep the password in your VPS secret store or in a permissions-restricted libpq password file; do not commit it to source control.
Rank #2
- Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
- Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
- Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
- Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
- Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth
The PostgreSQL client environment reference documents PGHOST, PGPORT, PGDATABASE, PGUSER, and PGSSLMODE. It also warns that PGPASSWORD can be visible to other users through process inspection. Treat it as unsuitable for durable secret management. An environment variable supplied by a protected service manager can be useful at runtime, but the secret itself should come from a secret-management system or protected file.
Configure PostgreSQL to accept only the required traffic
Find the Ubuntu configuration files
On Ubuntu, the PostgreSQL configuration directory is below:
/etc/postgresql/<version>/main
The two files that matter for a remote application connection are postgresql.conf, which controls listening behavior, and pg_hba.conf, which controls host-based authentication.
Free tools Windows power users keep installed
One-click scans. No signup required.
Set the listener address
In postgresql.conf, set listen_addresses only as broadly as the topology requires. A local-only deployment can remain on loopback. A database serving an application on another host must listen on the private address or other interface used by that application. Binding to every interface is broader than necessary and increases the chance that a firewall mistake exposes the service.
# postgresql.conf
listen_addresses = '10.0.0.10'
Replace the example address with the database VPS’s actual private address. If you change the listener, make sure the hostname in the client connection resolves to an address that PostgreSQL is listening on.
Add a narrow pg_hba.conf rule
pg_hba.conf is evaluated for the incoming connection. Add a rule that names the application source CIDR, database, role, and authentication method. For a TLS-only TCP connection, use hostssl and SCRAM authentication:
# pg_hba.conf
hostssl app_db app_user 10.0.1.25/32 scram-sha-256
The example permits only the single application address 10.0.1.25. If the application runs in a private subnet, use that subnet’s actual CIDR instead of widening the rule to all addresses. Place the rule where it will be selected before a broader rule that might reject or authenticate the connection differently. A rule that does not match the source address, database, or role cannot be fixed by changing the Python password alone.
Rank #3
- 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
- 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
- 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
- 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
- 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
hostssl rejects non-TLS TCP connections for that rule. If you use a plain host rule, the connection may be encrypted only when the client requests it; enforce the requirement in the client with sslmode and prefer a hostssl rule when the server policy must reject cleartext TCP.
Restrict the VPS and cloud firewall
Allow the PostgreSQL port only from the application server’s private address or application network. Do not open the port to the entire internet when the application has a stable private source. Apply both layers: the external VPS or cloud firewall limits who can reach the machine, while pg_hba.conf limits which database, role, and authentication method a reachable client can use.
After changing the Ubuntu configuration, restart the service:
sudo systemctl restart postgresql.service
A restart applies the listener and authentication changes. If the service fails to restart, inspect the PostgreSQL service status and logs before changing client settings; a syntax error in either configuration file prevents the intended policy from taking effect.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Build a secure Psycopg connection
Use keyword parameters for clear configuration
psycopg.connect() accepts keyword parameters as well as a libpq URI. Keeping the values in environment variables or a secret manager avoids putting credentials in source code. This example requires a CA file and validates the server certificate and hostname:
import os
import psycopg
conninfo = {
"host": os.environ["PGHOST"],
"port": os.getenv("PGPORT", "5432"),
"dbname": os.environ["PGDATABASE"],
"user": os.environ["PGUSER"],
"password": os.environ["PGAPP_PASSWORD"],
"sslmode": "verify-full",
"sslrootcert": os.environ["PGSSLROOTCERT"],
"connect_timeout": 10,
}
with psycopg.connect(**conninfo) as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1")
print(cur.fetchone())
The outer context manager closes the connection deterministically. The cursor context manager closes the cursor, and the connection context commits a successful block or rolls it back if an exception escapes. The SELECT 1 query is a minimal application-level check: it proves that Python reached PostgreSQL, authenticated, established the requested security mode, and could execute a query.
Understand each connection parameter
| Parameter | Purpose | Operational requirement |
|---|---|---|
host |
DNS name or address of the PostgreSQL server | It must resolve to an interface PostgreSQL listens on and must match the certificate name when using verify-full. |
port |
TCP listener port | Use the server’s configured PostgreSQL port and permit that port only from the application network. |
dbname |
Database to open | The database must exist and be allowed by the selected pg_hba.conf rule. |
user |
PostgreSQL login role | Use the least-privilege application role, not a superuser. |
password |
Role credential | Load it from protected runtime configuration or a secret store, never from committed source. |
sslmode |
Client TLS policy | verify-full provides encryption, CA validation, and hostname matching. |
sslrootcert |
Trusted CA bundle or certificate file | The file must contain a CA that can validate the server certificate and be readable by the application process. |
connect_timeout |
Maximum wait for a connection attempt | A finite value such as 10 seconds prevents a failed network path from hanging indefinitely. |
Use a libpq URI when your deployment supplies one
Psycopg also accepts a PostgreSQL/libpq URI. A URI is convenient when a platform injects one connection setting, while keyword parameters are easier to audit when you need separate environment variables and an explicit CA path. Whichever form you use, retain the same TLS, timeout, least-privilege, and secret-handling policies.
Rank #4
- 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
- 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
- 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
- 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
- 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
Configure TLS correctly
For a network connection, encryption alone is not enough. PostgreSQL’s SSL documentation explains that certificate verification is not performed by default unless you configure it. Without verification, a client can encrypt traffic while still failing to authenticate the server it reached.
Prefer sslmode=verify-full
verify-full requires TLS, validates the server certificate against the trusted CA, and checks that the requested hostname matches the certificate. Set host to the DNS name covered by the certificate, not an unrelated alias or raw address, unless the certificate explicitly contains that address.
The CA file supplied through sslrootcert must be present on the VPS, readable by the application user, and capable of building a chain to the server certificate. Keep the system clock correct; an incorrect clock can make an otherwise valid certificate appear expired or not yet valid.
Know what sslmode=require does not do
sslmode=require requires encryption but does not provide the same hostname validation as verify-full. It can be useful for a controlled transition when certificate verification is not yet available, but it should not be treated as equivalent server authentication. When the server policy is TLS-only, pair the client setting with a matching hostssl rule.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Keep runtime secrets out of source control
Set non-secret connection properties in the standard PostgreSQL variables when convenient:
PGHOST=db.internal.example
PGPORT=5432
PGDATABASE=app_db
PGUSER=app_user
PGSSLMODE=verify-full
PGSSLROOTCERT=/etc/myapp/postgres-ca.crt
Load the password separately as PGAPP_PASSWORD in the protected runtime environment used by the application service, or read it from a permissions-restricted password file or secret manager. Avoid putting a password in a repository, deployment manifest checked into source control, shell history, or a process argument. PostgreSQL specifically cautions that PGPASSWORD may be visible to other users through process inspection, so it is not a durable replacement for a protected secret mechanism.
Restrict file permissions on any CA bundle and password file to the account that runs the application. Rotate the role password through the secret-management process, then restart or reload the application with the new value. Do not print the connection dictionary or full URI in logs; it may contain the password and certificate paths.
Best Value
- 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
- 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
- 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
- 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
- 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
Test the connection in a controlled sequence
- Check name resolution. Confirm that the database hostname resolves on the application VPS to the intended private or approved address. A name resolving to a public address can bypass the network design you intended.
- Check the route and port. Verify that the application host can reach the PostgreSQL TCP port through its private network and firewall policy. A timeout before PostgreSQL responds usually indicates DNS, routing, a cloud or VPS firewall, a listener address, or a blocked port.
- Check the listener. Confirm that PostgreSQL is running and listening on the expected interface and port. If it listens only on loopback while the application is remote, no client-side password or TLS change can solve the problem.
- Check the selected
pg_hba.confrule. Match the application source CIDR, requested database, role, and connection type. Remember that PostgreSQL uses the first applicable rule; a preceding rule can change the result. - Check credentials. An authentication error after the server is reachable points to the role, database, password, or authentication method. Confirm that the role is permitted by the matching rule and that the password was rotated consistently in the server and secret store.
- Check certificates. A TLS error points to the CA file, certificate chain, hostname mismatch, certificate validity period, or system clock. With
verify-full, the hostname inPGHOSTmust be covered by the server certificate. - Run the minimal Python test. Execute the
SELECT 1program under the same user and service environment that runs the application. A test from an interactive shell can succeed while the service fails if the service receives different variables or file permissions.
Interpret common failure symptoms
| Symptom | Most likely layer | What to inspect |
|---|---|---|
| Connection waits until the timeout | DNS, routing, firewall, listener, or blocked port | Hostname resolution, private route, VPS/cloud firewall, listen_addresses, port, and whether PostgreSQL is running. |
| Connection is refused immediately | No process is listening at the destination, or the address is actively rejecting traffic | PostgreSQL service status, listener address, port, and local firewall policy. |
| “No pg_hba.conf entry” or a host authentication rejection | Host-based authentication policy | Source CIDR, database name, role name, connection type, rule order, and whether the rule uses hostssl. |
| Password authentication failed | Credentials or role configuration | Role name, password rotation, selected database, and the authentication method in the matching rule. |
| Certificate verify or hostname error | TLS identity validation | sslrootcert, CA chain, certificate hostname, certificate dates, and VPS clock. |
| Works in a shell but fails in the service | Different runtime environment or file permissions | Service-level environment variables, secret injection, CA-file ownership, and the application user. |
Psycopg can emit connection-time diagnostics through Python’s standard logging module. Enable verbose connection logging temporarily while diagnosing a failure, then disable it or reduce its level. Connection diagnostics can expose hostnames, usernames, and other sensitive deployment details, so do not leave them enabled indiscriminately in production.
Use pooling and asynchronous connections only when the application needs them
A single short-lived script can open one connection with a context manager and close it when the work finishes. A web application with concurrent requests should not create an unlimited number of new TCP and PostgreSQL sessions. Psycopg provides psycopg_pool for connection pooling; configure the pool size to match the database’s capacity and the application’s actual concurrency rather than treating it as unlimited.
Keep transactions short. Hold a connection while executing the required statements, commit or roll back deterministically, and return the connection to the pool promptly. Long-running idle transactions can retain locks and delay cleanup even when the Python request appears finished.
If the framework is based on asyncio, Psycopg also provides asynchronous connections and pooling APIs. Use the asynchronous interface consistently with the framework’s event loop; do not block an async request handler with synchronous database work. The same network, TLS, role, firewall, and timeout requirements still apply.
Self-managed PostgreSQL versus managed hosting
Running PostgreSQL on your own VPS gives you direct control over the listener, pg_hba.conf, firewall, certificates, package updates, and data location. It also makes you responsible for every operational task. A managed PostgreSQL service or managed VPS can move some of that work to the provider, but the exact boundary varies by service and region; verify it before choosing one.
| Concern | Self-managed PostgreSQL on a VPS | Managed PostgreSQL or managed VPS |
|---|---|---|
| Network isolation | You configure private interfaces, firewall rules, and pg_hba.conf. |
The provider may offer private networking and access controls; you must verify the available controls. |
| TLS certificates | You install the trusted CA and maintain server certificate configuration. | The provider may manage server certificates and publish a CA bundle; confirm hostname and client requirements. |
| Backups and restore | You design, schedule, monitor, and test backups and restores. | Backup retention and restore features depend on the service plan and must be checked explicitly. |
| Patching | You apply PostgreSQL and operating-system updates. | The provider may handle some updates, but maintenance windows and supported versions vary. |
| Connection pooling | You add and operate a pool such as Psycopg’s pool. | A service may offer a pooler, but limits and configuration are provider-specific. |
| Observability and failover | You build monitoring, alerting, replication, and recovery procedures. | These may be included or optional; verify metrics, failover behavior, and recovery objectives. |
| Total operating cost | Lower service abstraction, but your time and infrastructure tasks remain your responsibility. | Higher service abstraction can reduce operations work, with pricing and scope varying by provider. |
Regardless of hosting model, the Python side should still use a least-privilege role, a finite connect_timeout, protected credentials, and certificate verification appropriate to the service’s documented CA and hostname.
A production readiness checklist
- Psycopg 3 is installed in the application’s virtual environment and its supported Python/PostgreSQL combination has been checked.
- The application uses a dedicated PostgreSQL role and database rather than a superuser.
- The database listener is bound only to the interface required by the topology.
- The VPS or cloud firewall permits the PostgreSQL port only from the application network.
pg_hba.confnames the intended source CIDR, database, role, andscram-sha-256; usehostsslwhen TCP must be TLS-only.- The PostgreSQL service was restarted after configuration changes and is healthy.
- The client uses
sslmode=verify-fullwith a trusted CA file and a hostname covered by the server certificate. - The password is supplied through protected runtime configuration, a restricted password file, or a secrets manager, not committed source or an exposed process environment.
connect_timeoutis finite, and application logs do not print complete connection strings or passwords.- Connection and cursor lifetimes are deterministic; pooling or asynchronous APIs are used only when the application’s concurrency model requires them.
Bottom line
A secure Python-to-PostgreSQL connection on a VPS is a coordinated server, network, authentication, and client configuration. Install Psycopg 3, isolate an application role, permit only the application network, require SCRAM and TLS, verify the server with verify-full, protect the password, and troubleshoot from DNS and reachability through pg_hba.conf, credentials, and certificates. That sequence prevents most remote-connection failures and avoids turning a working database port into an unnecessarily exposed service.
Quick Recap
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.

