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.
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.
# 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
- Close embedded servers/sockets in teardown so the port is released.
- Avoid
server.port=8080in test config; useserver.port=0(random). - 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.