Cloud Explainers

How to Fix PostgreSQL 'Could Not Connect to Server'

PostgreSQL7 min video

'Could not connect to server: Connection refused' means your connection never reached the password. On a real Ubuntu 24.04 server with PostgreSQL 16.15 we find each place it stops: a server that isn't running (while systemctl calls it active), PostgreSQL listening on localhost only, a reload that changes nothing, a pg_hba.conf line that's missing, and a firewall that turns the refusal into a timeout.

Refused before the password

Your app says it could not connect to the PostgreSQL server. You restarted the app. Same error. An ice rink's booking site should list today's sessions. Instead: connection refused. The good news: the password is fine. The server never got far enough to ask for it.

Refused before the password: browser screenshot from the video

Where a connection can stop

So where can a connection stop? Your app finds the server's address, then knocks on port five four three two, PostgreSQL's usual port. On the way, a firewall can drop the knock, and the app just waits, sometimes for minutes. If nothing listens on that port, the server's machine says no at once: refused. If PostgreSQL does listen, its rules file, pg_hba.conf, decides whether this address may log in, and only then comes the password.

Where a connection can stop: diagram of Booking server, Firewall, Port 5432, pg_hba.conf, Password, rink-db

First, take the app out of it. From the booking server, psql, PostgreSQL's own client: dash h for the server, dash U for the user, then the database. It gets the same refusal, and pg_isready, a quick check that ships with it, gets no response. An older psql words it the way you may have searched it: could not connect to server. Same failure, older wording.

rink-web, and an older laptop with psql 12
psql -h rink-db -U rink rinkpsql: error: connection to server at "rink-db" (192.168.71.10), port 5432 failed: Connection refused
  Is the server running on that host and accepting TCP/IP connections?
rink-web, and an older laptop with psql 12
pg_isready -h rink-dbrink-db:5432 - no response
rink-web, and an older laptop with psql 12
psql -h rink-db -U rink rinkpsql: error: could not connect to server: Connection refused
  Is the server running on host "rink-db" (192.168.71.10) and accepting
  TCP/IP connections on port 5432?

Is PostgreSQL even running?

The usual fix first: is it even running? On the database server itself, psql doesn't use the network. Run as postgres, the database's own administrator account, it uses a socket, a file PostgreSQL creates while it runs. No such file: the server isn't running. So, a restart. It prints nothing, and psql fails exactly the same way.

Ana on the database server, rink-db
sudo -u postgres psqlpsql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
  Is the server running locally and accepting connections on that socket?
Ana on the database server, rink-db
sudo systemctl restart postgresql

Guess first: what does systemctl status say about postgresql? Active. Active, exited. On Ubuntu, that unit is only a wrapper that starts the clusters, a cluster being one running PostgreSQL with its own data and port. pg_lsclusters lists the real ones: sixteen main, port five four three two, down.

Ana on the database server, rink-db
systemctl status postgresql● postgresql.service - PostgreSQL RDBMS
  Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; preset: enabled)
  Active: active (exited) since Tue 2026-11-17 19:42:30 UTC; 23ms ago
  Process: 232 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
  Main PID: 232 (code=exited, status=0/SUCCESS)
  CPU: 527us

Nov 17 19:42:30 rink-db systemd[1]: Starting postgresql.service - PostgreSQ…S...
Nov 17 19:42:30 rink-db systemd[1]: Finished postgresql.service - PostgreSQ…BMS.
Hint: Some lines were ellipsized, use -l to show in full.
Ana on the database server, rink-db
pg_lsclustersVer Cluster Port Status Owner  Data directory  Log file
16  main  5432 down  postgres /var/lib/postgresql/16/main /var/log/postgresql/postgresql-16-main.log

So start the real one: postgresql at sixteen dash main. Now it fails out loud. The reason is in PostgreSQL's log: invalid value for shared_buffers, five twelve, lower case m b. Units are case sensitive. Last night someone raised the memory with a lower case unit, and that night's restart failed just as quietly.

Ana on the database server, rink-db
sudo systemctl start postgresql@16-mainJob for postgresql@16-main.service failed because the service did not take the steps required by its unit configuration.
See "systemctl status postgresql@16-main.service" and "journalctl -xeu postgresql@16-main.service" for details.
Ana on the database server, rink-db
sudo tail -n 5 /var/log/postgresql/postgresql-16-main.log2026-11-17 19:42:30.818 GMT [248] LOG:  invalid value for parameter "shared_buffers": "512mb"
2026-11-17 19:42:30.818 GMT [248] HINT:  Valid units for this parameter are "B", "kB", "MB", "GB", and "TB".
2026-11-17 19:42:30.818 UTC [248] FATAL:  configuration file "/etc/postgresql/16/main/postgresql.conf" contains errors
pg_ctl: could not start server
Examine the log output.
Ana on the database server, rink-db
grep -n '^shared_buffers' /etc/postgresql/16/main/postgresql.conf130:shared_buffers = 512mb  # min 128kB

The fix is two capital letters: five twelve, capital M, capital B. And the comment on the next line says: change requires restart.

Two capital letters: code change of /etc/postgresql/16/main/postgresql.conf, shared_buffers = 512MB # min 128kB (units are case sensitive)

Start it again. This time, nothing printed means it worked: pg_lsclusters says online.

Ana on the database server, rink-db
sudo systemctl start postgresql@16-main
Ana on the database server, rink-db
pg_lsclustersVer Cluster Port Status Owner  Data directory  Log file
16  main  5432 online postgres /var/lib/postgresql/16/main /var/log/postgresql/postgresql-16-main.log

Running again

PostgreSQL is running again, so the booking site should be back. Guess first: does the booking server connect now? No. Still refused.

Ana on the booking server, rink-web
psql -h rink-db -U rink rinkpsql: error: connection to server at "rink-db" (192.168.71.10), port 5432 failed: Connection refused
  Is the server running on that host and accepting TCP/IP connections?

On the database server, ss lists what's listening. PostgreSQL is on port five four three two, but only at one twenty-seven dot zero dot zero dot one, localhost: the address only this machine can reach. Its setting, listen_addresses, says localhost. That's the default after you install it.

Ana on the database server, rink-db
sudo ss -ltn 'sport = :5432'State  Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process
LISTEN  0  200  127.0.0.1:5432  0.0.0.0:*
Ana on the database server, rink-db
sudo -u postgres psql -c 'SHOW listen_addresses' listen_addresses
------------------
 localhost
(1 row)

Think of a shop. Shutters down: nobody's in, and you know at once. Open, but only by the staff door: from the street it looks just as closed. That's localhost. The road blocked: you never get there, you just wait. And at the door, a list of who may come in.

Like a shop, from the street: comparison table of At the shop vs What psql says, Not running, localhost only, Firewall, pg_hba.conf

A star in listen_addresses means every address this server has. Ana puts it in its own file in the conf.d folder, and reloads. It prints nothing. The booking server tries again: refused. The log says why: listen_addresses cannot be changed without restarting the server. A reload re-reads the settings, but this one only counts when the server starts.

Ana: database server and booking server
echo "listen_addresses = '*'" | sudo tee /etc/postgresql/16/main/conf.d/listen.conflisten_addresses = '*'
Ana: database server and booking server
sudo systemctl reload postgresql@16-main
Ana: database server and booking server
psql -h rink-db -U rink rinkpsql: error: connection to server at "rink-db" (192.168.71.10), port 5432 failed: Connection refused
  Is the server running on that host and accepting TCP/IP connections?
Ana: database server and booking server
sudo tail -n 3 /var/log/postgresql/postgresql-16-main.log2026-11-17 19:42:33.301 UTC [275] LOG:  received SIGHUP, reloading configuration files
2026-11-17 19:42:33.302 UTC [275] LOG:  parameter "listen_addresses" cannot be changed without restarting the server
2026-11-17 19:42:33.302 UTC [275] LOG:  configuration file "/etc/postgresql/16/main/conf.d/listen.conf" contains errors; unaffected changes were applied

So restart the cluster. Now ss shows zero dot zero dot zero dot zero: every address.

Ana on the database server, rink-db
sudo systemctl restart postgresql@16-main
Ana on the database server, rink-db
sudo ss -ltn 'sport = :5432'State  Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process
LISTEN  0  200  0.0.0.0:5432  0.0.0.0:*
LISTEN  0  200  [::]:5432  [::]:*

So which changes need a restart? The settings that decide how the server starts: the addresses it listens on, its port, its memory. pg_hba.conf, the list of who may log in, is read again on a reload. And postgresql.conf says which is which, in a comment next to each one.

Reload or restart?: comparison table of What it is vs Takes effect after, listen_addresses, port, shared_buffers, pg_hba.conf, In postgresql.conf

A new error means progress

And the booking server gets a different error. No pg_hba.conf entry for host one ninety-two dot one sixty-eight dot seventy-one dot twenty, user rink, database rink. That's progress. The knock reached PostgreSQL, and it answered: its rules file has no line for this address yet. psql asks twice, with encryption and without, so the line shows twice.

Ana on the booking server, rink-web
psql -h rink-db -U rink rinkpsql: error: connection to server at "rink-db" (192.168.71.10), port 5432 failed: FATAL:  no pg_hba.conf entry for host "192.168.71.20", user "rink", database "rink", SSL encryption
connection to server at "rink-db" (192.168.71.10), port 5432 failed: FATAL:  no pg_hba.conf entry for host "192.168.71.20", user "rink", database "rink", no encryption

Ana adds a host line: database rink, user rink, from the booking server's address, slash thirty-two meaning that one address only, checked with a password, scram. For this file, a reload is enough. psql asks for the password, and there are today's three sessions.

Ana: database server and booking server
echo 'host  rink  rink  192.168.71.20/32  scram-sha-256' | sudo tee -a /etc/postgresql/16/main/pg_hba.confhost  rink  rink  192.168.71.20/32  scram-sha-256
Ana: database server and booking server
sudo systemctl reload postgresql@16-main
Ana: database server and booking server
psql -h rink-db -U rink rink -c 'SELECT * FROM sessions'Password for user rink:
  starts  |  name  | places
----------+----------------+--------
 10:00:00 | Learn to skate |  6
 13:30:00 | Public skate  |  41
 19:00:00 | Hockey drop-in |  3
(3 rows)

And the rink's website lists them too: learn to skate at ten, and three places left for hockey.

A new error means progress: browser screenshot from the video

One more cause hides behind the same refusal: the wrong port. Ask for five four three three, where nothing listens, and you're refused at once.

Ana on the booking server, rink-web
psql -h rink-db -p 5433 -U rink rinkpsql: error: connection to server at "rink-db" (192.168.71.10), port 5433 failed: Connection refused
  Is the server running on that host and accepting TCP/IP connections?

When it hangs instead

A week later, the page takes ten seconds, then says: timeout expired. A different word. Refused is an answer. A timeout means no answer came back at all.

When it hangs instead: browser screenshot from the video

The server is up: ping gets its answers. psql, with a ten second limit, times out. Without a limit, it waited a hundred and thirty-two seconds before it gave up.

Ana on the booking server, rink-web
ping -c 2 -n rink-dbPING rink-db (192.168.71.10) 56(84) bytes of data.
64 bytes from 192.168.71.10: icmp_seq=1 ttl=64 time=0.179 ms
64 bytes from 192.168.71.10: icmp_seq=2 ttl=64 time=0.176 ms

--- rink-db ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1052ms
rtt min/avg/max/mdev = 0.176/0.177/0.179/0.001 ms
Ana on the booking server, rink-web
PGCONNECT_TIMEOUT=10 psql -h rink-db -U rink rinkpsql: error: connection to server at "rink-db" (192.168.71.10), port 5432 failed: timeout expired

Here's the difference on the wire. Refused: the app asks to connect, and the server's machine answers no straight away. Dropped: the firewall throws the request away. The app asks again, and again, and hears nothing. It's the blocked road from the shop: you never arrive, you just wait.

Refused answers. Dropped stays silent.: diagram of rink-web, Firewall, rink-db, connect to 5432, no: refused, again, again: nothing for 132 s, Refused is an answer. A timeout is silence.

On the database server, ufw, Ubuntu's firewall, has been switched on, and it lets only SSH in. Everything else is dropped without a word. Allow the rink's network to port five four three two, and the booking server counts its three sessions again.

Ana: database server and booking server
sudo ufw statusStatus: active

To  Action  From
--  ------  ----
22/tcp  ALLOW  Anywhere
Ana: database server and booking server
sudo ufw allow from 192.168.71.0/24 to any port 5432Rule added
Ana: database server and booking server
psql -h rink-db -U rink rink -c 'SELECT count(*) FROM sessions'Password for user rink:
 count
-------
  3
(1 row)

Before you call it fixed

Before you call it fixed, check from the app's own machine. pg_isready said no response before; now it says accepting connections. And after any change to postgresql.conf, restart, then look at pg_lsclusters, because a failed restart can stay silent.

Ana: database server and booking server
pg_isready -h rink-dbrink-db:5432 - accepting connections
Ana: database server and booking server
pg_lsclustersVer Cluster Port Status Owner  Data directory  Log file
16  main  5432 online postgres /var/lib/postgresql/16/main /var/log/postgresql/postgresql-16-main.log

Recap

So read the error's last words. No such file: not running. Refused: nothing listens at that address and port. Timeout: a firewall. No pg_hba.conf entry: you got through; add a line.

Read the error's last words: diagram of No such file or directory, Connection refused, timeout expired, no pg_hba.conf entry

If your app is talking to its database again, subscribing brings more fixes, run on real servers.

Every error in this video came from a real PostgreSQL server, and every command and the lab files are linked in the description. Thanks for watching Cloud Explainers.

Sources

Demos: containers on our own Mac standing in for an ice rink's booking server and database server; the rink and its sessions are made up. Every error and log line was real. Watch the full video on YouTube.

More videos

Python8 min

How to Fix Python ModuleNotFoundError: No Module Named

Go (Golang)5 min

Golang Pointers in 5 Minutes

Kubernetes8 min

How to Fix a Kubernetes Pod Stuck in CrashLoopBackOff

Homelab & self-hosting9 min

How to Fix a Homelab ESXi Host Not Responding

PostgreSQL24 min

PostgreSQL: Full Tutorial for Beginners

Load balancing & Nginx9 min

How a Load Balancer Works with HAProxy

Python9 min

How Python Virtual Environments Work

Homelab & self-hosting9 min

How to Fix Cloudflare Tunnel Errors in a Homelab

APIs9 min

How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'

Auth (OAuth, JWT)9 min

How Authenticator App Login Codes Work (TOTP)

Git22 min

Git and GitHub: Full Tutorial for Beginners

Homelab & self-hosting10 min

How a Homelab Hypervisor Works (VMware ESXi)

Kubernetes9 min

How to Fix Kubernetes ImagePullBackOff Errors

DNS8 min

How to Fix DNS 'Temporary Failure in Name Resolution' on Linux

AWS8 min

How to Fix AWS CLI 'Unable to Locate Credentials'

Homelab & self-hosting10 min

Proxmox vs ESXi for Your Homelab: When Each One Wins

PostgreSQL10 min

PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?

Kubernetes21 min

Kubernetes: Full Tutorial for Beginners

Networking9 min

How TCP Sockets Work

Claude & the Claude Developer Platform9 min

Claude Code Hooks Will Finally Make Sense After This

DevOps & CI/CD9 min

DevOps with Ansible Will Finally Make Sense After This

Networking9 min

How SNMP Network Monitoring Works

Git8 min

How to Fix GitHub 'Permission Denied (publickey)' Errors

Docker21 min

Docker: Full Tutorial for Beginners

PostgreSQL7 min

How to Fix PostgreSQL 'Password Authentication Failed'

Linux8 min

Why One Linux Server Handles More Users Than You Think

Networking7 min

How to Fix Network 'Connection Refused' Errors

DevOps & CI/CD9 min

DevOps Pipelines: Jenkins vs GitHub Actions

Linux11 min

Linux Nginx Reverse Proxy: Full Tutorial for Beginners

Networking11 min

Every Networking Term a Beginner Needs in 12 Minutes

Docker6 min

How to Fix Docker 'Permission Denied' on docker.sock

Git7 min

How to Fix Git 'Updates Were Rejected' When You Push

Linux7 min

How to Fix nginx 502 Bad Gateway Errors on Linux

Linux8 min

How to Fix Linux apt 'Could Not Get Lock' Errors (Ubuntu)

Networking9 min

How Email Works on the Internet (SMTP) in 10 Minutes

Python8 min

The Python Roadmap for Beginners

Go (Golang)21 min

Golang REST API with Gin: Full Tutorial for Beginners

Networking10 min

How a WireGuard VPN Network Works

Linux9 min

Linux Makefiles Will Finally Make Sense After This

Auth (OAuth, JWT)9 min

SAML vs OAuth vs OpenID Connect: What's the Difference?

Python7 min

How to Fix Python cron Jobs That Never Run

Linux22 min

Linux Bash Scripting: Full Tutorial for Beginners

Networking10 min

How PXE Network Boot Works

Active Directory9 min

How Active Directory Works

Linux10 min

How to Fix a Linux systemd Service That Won't Start

Linux9 min

Linux Logs: syslog vs journald

Auth (OAuth, JWT)9 min

JWT vs Session Cookies: Which One Should You Use?

Docker10 min

Docker vs Docker Compose: Which One Should You Use?

Docker9 min

How to Fix Docker Compose Containers That Can't Talk to Each Other

Django (Python web framework)22 min

Django Full Tutorial for Beginners

Linux9 min

How Linux systemd Works

Networking8 min

How to Fix 'Windows Cannot Access' Network Share Errors (SMB)

APIs10 min

REST vs gRPC: Which One Should You Use?

Certificates & PKI (ADCS)9 min

How to Fix SSL Certificate Chain Errors (Missing Intermediate)

Python9 min

Every Python Concept for Beginners in 10 Minutes

Databases & SQL9 min

Every SQL Join Type in 10 Minutes

OpenRouter (one API for many AI models)9 min

Why OpenRouter Free Models Hit Their Limit So Fast

Gemini API & Google AI Studio9 min

Why Your Gemini API Free Tier Runs Out So Fast

OpenRouter (one API for many AI models)10 min

OpenRouter Will Finally Make Sense After This

Caching & Redis10 min

How Redis Caching Works

Gemini API & Google AI Studio10 min

Gemini API vs Vertex AI: Which One Should You Use?

Gemini API & Google AI Studio8 min

How to Fix a Leaked Gemini API Key

Go (Golang)9 min

Why Golang Uses Goroutines Instead of Threads

Gemini API & Google AI Studio9 min

How to Fix Gemini API Error 429: Resource Exhausted

Claude & the Claude Developer Platform10 min

Claude Token Pricing Will Finally Make Sense After This

Python11 min

Why Python Web Scraping Returns Nothing (and the Fix)

Python10 min

Python uv vs pip: Which One Should You Use?

Python22 min

Python Automation: Full Tutorial for Beginners

Auth (OAuth, JWT)9 min

How OAuth Login Works

Gemini API & Google AI Studio10 min

Google AI Studio Will Finally Make Sense After This

Docker10 min

What Happens When You Run a Docker Container

Claude & the Claude Developer Platform8 min

How to Fix Claude Code Billing Your API Key Instead of Your Plan

Auth (OAuth, JWT)9 min

Why Passkeys Can't Be Phished Like Passwords

PowerShell10 min

PowerShell vs Bash: Which One Should You Learn?

Linux10 min

The Linux Roadmap for Beginners

Django (Python web framework)9 min

Django vs FastAPI: Which One Should You Use?

Databases & SQL10 min

Why SQLite Is the Most Used Database in the World

Databases & SQL11 min

How a NoSQL Database Like MongoDB Works

Python11 min

How to Fix Python pip error: externally-managed-environment

Databases & SQL9 min

How to Fix MySQL Too Many Connections Database Errors

Go (Golang)9 min

Golang Concurrency Will Finally Make Sense After This

AWS10 min

How Amazon S3 Works

Kubernetes10 min

How Kubernetes Works

Git10 min

How Git Works

Docker10 min

How to Fix Docker Port Already Allocated Errors

PostgreSQL10 min

How PostgreSQL Works

Git8 min

How to Fix Git Merge Conflicts

Linux9 min

How to Fix No Space Left on Device in Linux

Networking10 min

How the Internet Works

Databases & SQL9 min

SQL vs NoSQL: When Each One Wins

Auth (OAuth, JWT)8 min

How to Fix JWT Token Expired Errors (401 Unauthorized)

Claude & the Claude Developer Platform9 min

Claude API vs Claude Pro: Why Your Subscription Doesn't Include It

AI agent skills9 min

Why AI Agent Skills Beat Giant Prompts

Linux10 min

Linux Cron Jobs Will Finally Make Sense After This

Cybersecurity10 min

Security Logs Will Finally Make Sense After This

Cybersecurity8 min

How to Fix a Security Leak: An API Key Pushed to GitHub

DNS9 min

DNS Will Finally Make Sense After This

Cybersecurity9 min

Never Ignore a Security Update

Auth (OAuth, JWT)9 min

Two-Factor Authentication Will Finally Make Sense

Networking8 min

Never Expose a Database to the Internet

Cybersecurity10 min

SSH Keys vs Passwords: Which Is Safer for Security?

Linux10 min

The 5 Levels of Linux Boot: From Power On to Login

Networking12 min

The 5 Levels of Network Firewalls

Cybersecurity10 min

Password Security: Why Hackers Crack Weak Passwords

Linux9 min

Why Your Linux Server Runs Out of Memory

Networking10 min

HTTP vs HTTPS: What Actually Changes on Your Network

Linux12 min

Every Linux File Permission You Need to Know

Linux10 min

Linux Processes vs Threads: When Each One Wins

Networking11 min

The OSI Model Will Finally Make Sense After This

Git11 min

The 7 Levels of Git

Networking10 min

Every Network Troubleshooting Command You Need

Cybersecurity10 min

Hashing vs Encryption in Cybersecurity: When Each One Wins

Networking11 min

Why the Internet Ran Out of IP Addresses

Linux11 min

Linux Package Managers: apt vs Snap vs Flatpak

Python9 min

Why Python Is Slow (and When It Doesn't Matter)

Networking11 min

TCP vs UDP: When Each One Wins

Linux8 min

Stop Running Linux as Root (Do This Instead)

Linux11 min

Linux Users and Groups Will Finally Make Sense

Cybersecurity9 min

Why Phishing Beats Good Security (and How to Spot It)

Docker12 min

The 7 Levels of Docker

AI agents & MCP12 min

AI Agents Will Finally Make Sense After This

Git8 min

Stop Using git push --force (Use This Instead)

AI agent skills10 min

Agent Skills vs MCP: When Each One Wins

Networking12 min

Networking Will Finally Make Sense After This

Linux12 min

Every Linux Command You Actually Need

Cybersecurity12 min

The 7 Levels of Cybersecurity

System design12 min

Every System Design Concept You Need, in One Diagram

PostgreSQL10 min

Why PostgreSQL Ignores Your Index