karatelabs/karate · error · RuntimeException

failed to find free port

Error message

failed to find free port

What it means

PortUtils.findFreePort() asks the OS for an ephemeral port by binding a ServerSocket to port 0 and returning its local port. If binding fails (socket subsystem unavailable, permission/security restrictions, resource exhaustion), it throws 'failed to find free port' wrapping the underlying exception.

Solutions

  1. Read the wrapped cause (e.getCause()) to identify the socket error; fix the underlying OS/network restriction
  2. In containers/CI, ensure the process is allowed to open server sockets (no restrictive network policy or seccomp filter)
  3. Reduce parallelism or reuse a shared port pool if ephemeral ports are exhausted (check with `ss -s` / netstat TIME_WAIT counts)
  4. Retry the call - port exhaustion is often transient
Defensive patterns

Strategy: retry

Try / catch

int port;
try {
    port = PortUtils.findFreePort();
} catch (RuntimeException e) {
    port = fallbackPortAllocator(); // e.g. precomputed range scan
}

Prevention

When it happens

Trigger: Calling PortUtils.findFreePort() when ServerSocket(0).bind fails - typically because the operating system denied socket creation, ephemeral port ranges are exhausted, or a security manager/firewall blocks opening server sockets.

Common situations: Running tests inside restricted containers/CI sandboxes without network socket permissions, heavy parallel test suites exhausting ephemeral ports (TIME_WAIT buildup), or misconfigured ephemeral port ranges on the host.

Related errors


AI-assisted analysis of karatelabs/karate@a22eb90246 (2026-09-12). Data as JSON: /api/errors/7931678d960e72b5. Report an issue: GitHub.

Appendix: source

Thrown at karate-core/src/main/java/io/karatelabs/process/PortUtils.java:118

                }
                logger.trace("HTTP {} returned {} (attempt {})", url, response.statusCode(), i + 1);
            } catch (Exception e) {
                logger.trace("HTTP {} not available (attempt {}): {}", url, i + 1, e.getMessage());
            }
            sleep(intervalMs);
        }
        logger.warn("HTTP {} not available after {} attempts", url, attempts);
        return false;
    }

    /**
     * Find a free port.
     */
    public static int findFreePort() {
        try (ServerSocket socket = new ServerSocket(0)) {
            return socket.getLocalPort();
        } catch (Exception e) {
            throw new RuntimeException("failed to find free port", e);
        }
    }

    private static void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

}

View on GitHub (pinned to a22eb90246)