Skip to content
Latchkey

Java "BindException: Address already in use" (Test Port) in CI

BindException: Address already in use means the test asked the OS for a port that is already taken - a hardcoded fixed port used by two tests/runs at once, or a previous server that did not shut down and still holds the socket.

What this error means

A test that starts an embedded server fails with java.net.BindException: Address already in use (or Web server failed to start. Port 8080 was already in use). Parallel tests or a leftover process clash on the fixed port.

junit
Caused by: java.net.BindException: Address already in use
        at java.base/sun.nio.ch.Net.bind0(Native Method)
***
Web server failed to start. Port 8080 was already in use.

Common causes

Hardcoded port reused concurrently

Two tests (or two runs on the same runner) bind the same fixed port at once, so the second fails.

Previous server did not release the port

An earlier test's server was not shut down (or lingers in TIME_WAIT), keeping the socket bound for the next attempt - often transient.

How to fix it

Bind an ephemeral port instead of a fixed one

Let the OS pick a free port so concurrent tests never collide.

java
# Spring Boot test: random port
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApiIT {
  @LocalServerPort int port;   // injected actual port
}

Ensure servers are stopped between tests

  1. Close embedded servers/sockets in teardown so the port is released.
  2. Avoid server.port=8080 in test config; use server.port=0 (random).
  3. If a leftover process holds the port, that is transient - a clean retry on a fresh runner clears it.

How to prevent it

  • Always bind random/ephemeral ports in tests, close servers in teardown, and never hardcode a fixed port for concurrent test execution.

Frequently asked questions

What causes ""java.net.BindException: Address already in use""?
Two tests (or two runs on the same runner) bind the same fixed port at once, so the second fails.
How do I fix "java.net.BindException: Address already in use"?
Let the OS pick a free port so concurrent tests never collide.
Can Latchkey fix this automatically?
Yes. Latchkey runs your GitHub Actions on managed runners that detect this failure, apply the fix, and retry the job automatically - self-healing is on by default.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card