python network_error ai_generated true

ConnectionRefusedError: [Errno 111] Connection refused

ID: python/pytest-docker-compose-not-ready

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2026-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

A test tries to connect to a service (e.g., database, Redis) that is not yet ready. This often happens in CI when using docker-compose without waiting for services to be healthy.

generic

中文

测试尝试连接尚未准备好的服务(例如数据库、Redis)。这通常发生在 CI 中使用 docker-compose 而没有等待服务健康时。

Workarounds

  1. 98% success
    In docker-compose.yml, add healthcheck to the service and use depends_on with condition: service_healthy.
  2. 95% success
    pip install pytest-docker
    Then use the docker_services fixture to wait for ports.
  3. 90% success
    @pytest.fixture
    def db_connection():
        for _ in range(30):
            try:
                conn = connect()
                break
            except ConnectionRefusedError:
                time.sleep(1)
        else:
            raise
        yield conn
        conn.close()

Dead Ends

Common approaches that don't work:

  1. 80% fail

    This is unreliable; services may take longer or shorter to start, leading to flaky tests.

  2. 90% fail

    If the service never starts, the test hangs forever.

  3. 95% fail

    This hides the issue and reduces test coverage.