php network_error ai_generated true

cURL error 7: Failed to connect to host port: Connection refused

ID: php/curl-error-7-connection-refused

Also available as: JSON · Markdown
85%Fix Rate
85%Confidence
150Evidence
2015-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
83 active

Root Cause

PHP's cURL cannot establish a TCP connection to the target host. Common in Docker environments where service names don't resolve, localhost doesn't map to the expected service, or the target service hasn't started yet.

generic

Workarounds

  1. 90% success In Docker, use the service name from docker-compose.yml instead of localhost
    # In .env or config:
    DB_HOST=mysql        # Not 'localhost' or '127.0.0.1'
    REDIS_HOST=redis     # Use the docker-compose service name
    API_HOST=api-service # The container's service name on the Docker network

    Sources: https://docs.docker.com/compose/networking/

  2. 88% success Add depends_on with health checks in docker-compose to ensure services start in order
    services:
      app:
        depends_on:
          mysql:
            condition: service_healthy
      mysql:
        healthcheck:
          test: ['CMD', 'mysqladmin', 'ping', '-h', 'localhost']
          interval: 5s
          timeout: 3s
          retries: 5

    Sources: https://docs.docker.com/compose/compose-file/05-services/#depends_on

  3. 85% success Verify the target service is listening on the expected port with correct bind address
    # Check if the service is listening:
    ss -tlnp | grep :3306
    # Ensure it's not bound to 127.0.0.1 only (in Docker it needs 0.0.0.0)
    # In MySQL config: bind-address = 0.0.0.0

Dead Ends

Common approaches that don't work:

  1. Increasing PHP cURL timeout values (CURLOPT_CONNECTTIMEOUT) 85% fail

    Connection refused (ECONNREFUSED) is an immediate TCP RST response, not a timeout issue. The port is unreachable and no amount of waiting will change that unless the target service starts.

  2. Switching from cURL to file_get_contents or stream contexts 95% fail

    The connection refusal is at the TCP level, not specific to cURL. All PHP HTTP methods will fail identically because the underlying socket connection is refused by the OS.

Error Chain

Leads to:
Frequently confused with: