How to Fix Docker Postgres Connection Refused Error
In this tutorial, you'll learn about How to Fix Docker Postgres Connection Refused Error. We cover key concepts, practical examples, and best practices.
Your application cannot connect to PostgreSQL running in Docker and gets Connection refused or could not connect to server — Postgres is not running, the port is not exposed, or the connection string is wrong.
The Problem
Error: connect ECONNREFUSED 127.0.0.1:5432
Or:
psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed:
Connection refused
Step-by-Step Fix
Step 1: Check if the Postgres container is running
docker ps | grep postgres
If empty, start it:
docker run -d --name postgres \
-e POSTGRES_USER=myuser \
-e POSTGRES_PASSWORD=mypassword \
-e POSTGRES_DB=mydb \
-p 5432:5432 \
postgres:15
Step 2: Check container logs
docker logs postgres
Expected:
LOG: database system is ready to accept connections
Step 3: Test connection from the host
psql -h localhost -U myuser -d mydb
Or use Docker's client:
docker exec -it postgres psql -U myuser -d mydb
Step 4: Verify port mapping
docker port postgres
Expected:
5432/tcp -> 0.0.0.0:5432
If port mapping is missing, stop and recreate the container with -p 5432:5432.
Step 5: Check PostgreSQL configuration inside the container
docker exec postgres cat /var/lib/postgresql/data/postgresql.conf | grep listen_addresses
Expected:
listen_addresses = '*'
If set to localhost, change it:
docker exec -it postgres bash -c "echo 'listen_addresses = *' >> /var/lib/postgresql/data/postgresql.conf"
docker restart postgres
Step 6: Check pg_hba.conf for authentication
docker exec postgres cat /var/lib/postgresql/data/pg_hba.conf
Ensure there is an entry for your host:
host all all 0.0.0.0/0 md5
Step 7: Test from another container on the same network
docker run --rm --network host postgres:15 psql -h localhost -U myuser -d mydb
Prevention Tips
- Use
-p 5432:5432to expose Postgres to the host - Set
POSTGRES_PASSWORDas a strong password - Use
POSTGRES_DBto create a default database - Keep Postgres on a dedicated Docker network
- Use the
postgres:15image (specific version) notlatest
Common Mistakes with postgres connect
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world DOCKER code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro