How to Debug “Connection Refused” Between Docker Compose Services

When working with Docker Compose, one of the most frustrating issues developers face is the dreaded “Connection Refused” error between services. This guide will walk you through common causes, debugging strategies, and practical solutions to ensure smooth inter-service communication.

Understanding the “Connection Refused” Error

In Docker Compose, multiple containers (e.g., a web app and a database) run on a shared network. If a service cannot establish a connection, you’ll often see:

curl: (7) Failed to connect to db port 3306: Connection refused
Docker Compose connection refused

This error usually means the target container is not listening, unreachable, or misconfigured.

Common Causes of “Connection Refused” in Docker Compose

  1. Using localhost instead of the service name
    • In Docker Compose, containers communicate via service names, not localhost.
  2. Service not ready when another container tries to connect
    • Example: a web app starts before the database finishes initializing.
  3. Port mismatch
    • The exposed port (ports: in Compose) may not match the internal container port.
  4. Firewall or binding issues
    • Service may be bound to 127.0.0.1 instead of 0.0.0.0.

Example: Web App and Database in Docker Compose

Let’s simulate a Python Flask app connecting to a PostgreSQL database.

ConnectionRefusedExample/
 ├─ docker-compose.yml
 └─ web/
    ├─ Dockerfile
    └─ app.py

docker-compose.yml

services:
  web:
    image: curlimages/curl:7.85.0
    depends_on:
      - db
    command: ["sh", "-c", "sleep 2 && curl db:3306"]

  db:
    image: mysql:8
    environment:
      MYSQL_ROOT_PASSWORD: secret

Flask app (web/app.py)

from flask import Flask
import psycopg2

app = Flask(__name__)

@app.route("/")
def index():
    try:
        conn = psycopg2.connect(
            dbname="mydb",
            user="user",
            password="secret",
            host="localhost",   #Using "localhost" here would cause "Connection Refused"
            port="5432"
        )
        return "Connected successfully!"
    except Exception as e:
        return f"Error: {e}"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

web/Dockerfile

FROM python:3.11-slim
WORKDIR /app
COPY app.py .
RUN pip install flask psycopg2-binary
CMD ["python", "app.py"]

Then, run command:

docker-compose up

Debugging Steps

1. Check if the container is running

docker-compose ps

Ensure db is up and healthy.

2. Inspect logs of the database

docker-compose logs db

Look for initialization messages.

3. Test connectivity inside the web container

docker-compose exec web ping db
docker-compose exec web nc -z db 5432

If these fail, the app cannot reach the database.

4. Ensure correct host name

Replace localhost with the service name (db).

5. Add depends_on and retry logic

  • depends_on ensures the web waits until db starts.
  • In real projects, add a healthcheck or retry loop.

Final Fixed Example

conn = psycopg2.connect(
    dbname="mydb",
    user="user",
    password="secret",
    host="db",   # Use service name
    port="5432"
)

Now, running:

docker-compose up

should start both containers, and the Flask app will successfully connect to PostgreSQL.

The “Connection Refused” error in Docker Compose often stems from simple misconfigurations like using localhost instead of a service name or services starting at different times. By carefully checking logs, testing connectivity inside containers, and using proper Compose configuration, you can debug and resolve this issue quickly.

This is the end of the How to Debug “Connection Refused” Between Docker Compose Services.

You can read more useful articles like How To Fix “No Space Left On Device” In Docker.

Follow us for the more helpful posts!

We hope this is a useful post for you.

 

0 0 votes
Article Rating
Aaron LX

Aaron LX

Aaron is a passionate writer, crazy about shopping, eCommerce and trends. Besides his outstanding research skills and a positive mind, Aaron eagerly shares his experience with the readers.

Leave a Reply or put your Question here

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x