Troubleshooting: psql Hangs on Connect over SSH Tunnel Proxy

Abstract: Resolve psql connection hangs over SSH tunnels by diagnosing network latency, firewall drops, and local port forwarding issues.

Created: 2026-08-29 by

When psql hangs on connect over an SSH tunnel proxy, the issue usually stems from network latency, firewall drop policies, or incorrect local port forwarding configuration. Immediate rejection is typical for authentication failures, so a silent hang indicates the TCP handshake is not completing. This guide details how to diagnose and resolve these connectivity stalls using standard SSH and PostgreSQL tools.

Understanding the Connection Flow

To troubleshoot effectively, you must understand the data path. When you use an SSH tunnel to access a remote PostgreSQL database, your local machine connects to the SSH server. The SSH server then acts as a relay, connecting to the target database host. If psql hangs, it means the initial TCP SYN packet is sent, but no SYN-ACK response is received within the timeout period. This behavior differs significantly from authentication errors. As noted in previous discussions, configuration issues in pg_hba.conf typically result in immediate connection refusals with specific error codes, not hangs. Therefore, a hanging connection points squarely to network-level blocking or resource exhaustion rather than database permission settings. You should verify that the SSH tunnel itself is established correctly before blaming the database server.

Verifying the SSH Tunnel State

The first step is to ensure the SSH tunnel is active and listening on the correct local port. Use the -L flag to forward a local port to the remote host. For example:
ssh -L 5432:localhost:5432 user@ssh-gateway
If this command fails to return a prompt, the SSH connection itself is blocked. Check if your local firewall is allowing outbound connections on port 22. Additionally, verify that the SSH gateway has internet access and can reach the PostgreSQL host. If the SSH session hangs indefinitely, the problem lies outside of psql entirely. For more insights on managing remote access securely, see Use SSH tunnel to access work PC apps from personal PC.

Diagnostics with Netcat and Traceroute

Isolate the failure point by testing connectivity at different layers of the network stack. Since psql relies on TCP, you can use netcat (or nc) to test raw socket connectivity without involving the PostgreSQL protocol. Run the following command while your SSH tunnel is active:
nc -vz localhost 5432
If nc also hangs, the issue is with the SSH tunnel or the local network interface. If nc connects instantly but psql hangs, the problem may be related to the PostgreSQL protocol negotiation or DNS resolution. You can also use traceroute or mtr to visualize the path. However, note that traceroute through an SSH tunnel requires careful configuration because the traffic is encapsulated. Standard external traceroutes will only show hops up to the SSH gateway, not beyond it. To debug further, check logs on the SSH gateway for dropped packets or rate limiting.

Checking Local Firewall Rules

Local firewalls on your client machine can sometimes interfere with loopback interfaces used by SSH tunnels. On Linux, check iptables or nftables rules. On macOS or Windows, review the built-in firewall settings. Ensure that the application launching psql is permitted to bind to local ports above 1024. A common pitfall is having multiple SSH agents or conflicting port bindings. Ensure no other process is occupying port 5432 locally. Use lsof -i :5432 to identify any existing listeners. If another service is holding the port, change the local forwarding port in your SSH command.

Optimizing SSH and PostgreSQL Settings

Network latency and timeout settings can cause apparent hangs. Adjusting SSH keep-alive messages can prevent intermediate firewalls from dropping idle connections. Add the following options to your SSH command:
ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=3 -L 5432:localhost:5432 user@gateway
These flags send keep-alive packets every 60 seconds, ensuring that NAT devices or firewalls do not consider the connection dead. On the PostgreSQL side, ensure that the server is configured to accept connections from the SSH gateway's IP address. Check postgresql.conf for the listen_addresses setting. It should include the gateway's IP or be set to * for all addresses. Remember, this does not cause hangs; misconfiguration here causes immediate rejections. For more on handling proxy traffic issues, refer to Proxy Server Forwarding Traffic Over Two Consecutive Proxies.

Common Pitfalls and Resolutions

Several subtle issues can mimic a hang. One is DNS resolution delays. If psql tries to resolve the hostname localhost via IPv6 first and your system lacks IPv6 support, it may timeout before falling back to IPv4. Force IPv4 by using 127.0.0.1 instead of localhost in your psql connection string. Another issue is large query execution time masquerading as a connection hang. If you are running a heavy query immediately after connecting, the client may appear stuck. Use psql -c "SELECT 1;" to test basic connectivity. If this returns instantly, your connection is fine, and the delay was caused by your workload. Finally, check for proxy interference. If your corporate network uses an HTTP proxy, it might intercept SSH traffic incorrectly. Configure your SSH client to bypass proxies for internal hosts using the ProxyCommand directive or environment variables like NO_PROXY.

Frequently Asked Questions

Why does psql reject connections immediately but hang in other cases?

Immediate rejections are handled by the application layer, where PostgreSQL sends an error message upon detecting invalid credentials or unauthorized IPs. Hangs occur at the transport layer when the TCP handshake cannot complete due to firewalls, routing issues, or lost packets.

Can pg_hba.conf settings cause psql to hang?

No, pg_hba.conf configurations result in immediate connection failures with clear error messages like "FATAL: password authentication failed." They do not cause silent timeouts or hangs because the database server actively responds to the connection attempt.

How do I force psql to use IPv4 to avoid DNS timeouts?

Specify the IP address 127.0.0.1 explicitly in your psql command or connection URI instead of using the hostname localhost. This bypasses DNS resolution entirely and forces the client to use the IPv4 loopback interface.

What is the best way to test if my SSH tunnel is working?

Use nc -vz localhost 5432 while the tunnel is active. If netcat reports a successful connection, the tunnel is functioning correctly. If it hangs, the issue is with the SSH configuration or network path, not PostgreSQL.

Should I increase the connection timeout in psql?

Increasing the timeout in psql using the -c option or environment variables only delays the error message; it does not fix the underlying network block. It is better to resolve the firewall or routing issue than to wait longer for a connection that will eventually fail.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More