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
- Read the wrapped cause (e.getCause()) to identify the socket error; fix the underlying OS/network restriction
- In containers/CI, ensure the process is allowed to open server sockets (no restrictive network policy or seccomp filter)
- Reduce parallelism or reuse a shared port pool if ephemeral ports are exhausted (check with `ss -s` / netstat TIME_WAIT counts)
- 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
- Cap test parallelism so ephemeral ports are not exhausted
- Run socket-dependent tests in environments that permit server sockets
- Cache one free port per test class instead of allocating repeatedly
- Tune the OS ephemeral port range (net.ipv4.ip_local_port_range)
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
- Could not start callback server on any configured port: " +…
- port : not available after attempts
- stop() failed
- port must be between 1 and 65535
- WebDriver session create failed: " + e.getMessage()
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)