Connection refused on docker container
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
A "connection refused" error when trying to reach a Docker container means that the network connection to the container was established at the transport level, but nothing was listening on the target port. This is one of the most common Docker networking issues and can stem from misconfigured port mappings, services binding to the wrong interface, or the container application not running correctly.
Common Causes
1. Service Binding to localhost Inside the Container
The most frequent cause is that the application inside the container is listening on 127.0.0.1 (localhost) instead of 0.0.0.0 (all interfaces). Inside a container, localhost refers to the container's own loopback, which is not reachable from outside:
For common frameworks:
2. Incorrect Port Mapping
The -p flag maps a host port to a container port. The syntax is HOST_PORT:CONTAINER_PORT:
3. Service Not Running Inside the Container
The application may have crashed on startup:
4. EXPOSE vs -p
The EXPOSE instruction in a Dockerfile is documentation only. It does not actually publish the port. You must use -p at runtime:
5. Docker Network Isolation
Containers on different Docker networks cannot reach each other by default:
Within the same network, containers can reach each other by container name.
How to Diagnose
Step 1: Verify the Container is Running
Step 2: Check Port Mappings
Step 3: Test from Inside the Container
Step 4: Check What the Service is Listening On
Look for the Local Address column. If it shows 127.0.0.1:8080, the service is only listening on localhost.
Docker Compose Example
In Docker Compose, use the ports directive:
Common Pitfalls
- Firewall rules: On Linux hosts,
iptablesorufwrules may block Docker's port mappings. Checksudo iptables -L -nif connections fail. - Docker Desktop on Mac/Windows: Docker runs in a VM, so
host.docker.internalis needed to reach the host machine from inside a container. - Health check timing: If you connect immediately after
docker run, the service may not have started yet. Add a health check or a brief wait. - Conflicting ports: If another process on the host is already using the mapped port, Docker will fail to bind it. Check with
lsof -i :8080.
Summary
| Symptom | Likely Cause | Fix |
| Connection refused from host | Service bound to 127.0.0.1 | Bind to 0.0.0.0 |
| Connection refused, container running | Wrong port mapping | Check -p HOST:CONTAINER order |
Container not in docker ps | Service crashed | Check docker logs |
| Containers cannot reach each other | Different networks | Use shared Docker network |

