Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java: java.net.BindException: Address already in use

The kernel refused the listening socket. Find the process holding the port, check the bound interface and privileged ports, then restart cleanly.

~5 min readJava
#java#bindexception#ports#troubleshooting
Bold white headline reading PORT IN USE beside a cyan Java socket crate blocked by an amber lock.

Introduction & Quick Summary

A Spring Boot service starts, then fails in the middle of the log:

code
java.net.BindException: Address already in use: bind at sun.nio.ch.Net.bind0(Native Method) at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:151) at org.apache.tomcat.util.net.NioEndpoint.initServerSocket(NioEndpoint.java:307)

Quick answer: the operating system refused to attach the listening socket to that port because another socket already owns it, or the process is not allowed to bind there. The Java stack trace ends at bind0, which is the kernel's answer, not a Java-level problem.

bash
ss -ltnp 'sport = :8080' # LISTEN 0 4096 *:8080 *:* users:(("java",pid=48213,fd=41))

Two causes cover most cases: a previous instance of the same application is still running, or something else owns the port. Less often the cause is an address the host does not have, a privileged port in a non-root container, or an IPv6/IPv4 mismatch. This guide covers how to find the holder, why TIME_WAIT is usually innocent, and how to make ports deterministic in tests and containers.

Core Mechanics, Signatures & Reproducible Setup

ServerSocket, ServerSocketChannel.bind and the frameworks built on them call bind(2). The kernel returns EADDRINUSE when the tuple (address, port, protocol) is already bound without SO_REUSEPORT, or EACCES when the port is privileged and the process lacks the capability. Java maps both to BindException, and the message text carries the platform wording.

java
import java.net.ServerSocket; public class Bind { public static void main(String[] args) throws Exception { try (ServerSocket s = new ServerSocket(8080)) { System.out.println("listening on " + s.getLocalSocketAddress()); Thread.sleep(60_000); } } }
bash
javac Bind.java && java Bind & # first instance java Bind # Address already in use: bind
Bind targetKernel checkTypical failure
new ServerSocket(8080)wildcard 0.0.0.0 or ::any other listener on the port
new ServerSocket(8080, 50, InetAddress.getByName("127.0.0.1"))loopback onlyanother loopback listener
new ServerSocket(0)kernel picks a free portalmost never fails
:80 as non-rootprivileged portPermission denied, also a BindException
IPv6 wildcard plus IPv4 listenerdual-stack overlapAddress already in use on the second bind
DiagnosticCommandShows
Listener with PIDss -ltnp 'sport = :8080'PID and process name
All listenersss -ltnports in use
Which processlsof -nP -iTCP:8080 -sTCP:LISTENalternative to ss
Socket statesss -tan 'sport = :8080'TIME_WAIT, ESTABLISHED
Container mappingdocker port <container>host to container mapping
Java-side checkjcmd <pid> VM.command_linethe actual -Dserver.port

Key Comparison Table

CauseEvidenceFix
Previous instance still runningss shows a java PID you recognisestop it, then restart
Another service owns the portPID belongs to another programchange the port or stop the service
Zombie child of a crashed supervisorparent gone, PID alivekill by PID, check the supervisor
Port bound to a different interfacelistener on 127.0.0.1:8080bind to the same address or stop it
Privileged port as non-rootPermission denied in the messageuse a high port or grant CAP_NET_BIND_SERVICE
Address not assigned to the hostbinding 192.168.1.50 that is not localuse 0.0.0.0 or the real address
Docker -p 8080:8080 twicehost-level conflict, container finechange host port
IPv6 dual-stack overlapsecond bind on :: fails while 0.0.0.0 workspick one family
ApproachCommandEffect
Kill the holderkill <pid>clean shutdown, port released
Forcekill -9 <pid>port released, no graceful close
Pick a free portserver.port=0kernel assigns, log shows the port
Reuse the addressSO_REUSEADDRhelps restart, not active listeners
Bind a specific interfaceserver.address=127.0.0.1narrows conflicts
Container override-e SERVER_PORT=8081 -p 8081:8081avoids host collision

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Finding who holds the port

bash
ss -ltnp 'sport = :8080' lsof -nP -iTCP:8080 -sTCP:LISTEN ps -o pid,ppid,etime,cmd -p <pid>

ss needs the right privileges to show the process name; inside a container it shows only processes in that namespace. If the port is held by a process you cannot see, check the host namespace with nsenter -t <pid> -n ss -ltnp or from the host directly.

2. TIME_WAIT is usually not the cause

bash
ss -tan state time-wait 'sport = :8080' | wc -l

TIME_WAIT applies to connections that were closed, not to the listening socket. A server that restarts immediately can fail when it tries to bind without SO_REUSEADDR while old connections linger, but Java's ServerSocket sets SO_REUSEADDR by default on most platforms, so a bind failure with thousands of TIME_WAIT sockets is usually a second live listener. Do not set tcp_tw_reuse to work around a problem that is not there.

3. Interface and address mismatches

java
new ServerSocket(8080, 50, InetAddress.getByName("192.168.1.50")); // BindException: Cannot assign requested address

Binding to an address the host does not own fails even when the port is free. 0.0.0.0 binds everything IPv4; :: binds IPv6 and, on Linux with net.ipv6.bindv6only=0, also IPv4. The combination is why a second process sees the port as taken on one family and free on the other:

bash
java -Djava.net.preferIPv4Stack=true -jar app.jar

Use that flag only as a diagnostic; the real fix is to bind one family consistently.

4. Privileged ports and containers

bash
java -jar app.jar --server.port=80 # BindException: Permission denied

Non-root containers cannot bind below 1024 without CAP_NET_BIND_SERVICE. The idiomatic answer is to listen on 8080 inside the container and map 80:8080 at the runtime. For Kubernetes, containerPort: 8080 and a Service with port: 80 keeps the app unprivileged.

securityContext: runAsNonRoot: true capabilities: add: ["NET_BIND_SERVICE"]

5. Spring Boot and Tomcat specifics

properties
server.port=8080 server.address=0.0.0.0 management.server.port=8081

Spring Boot fails fast with Web server failed to start. Port 8080 was already in use. and the cause is chained below. Actuator on a separate port doubles the chance of a collision. A server.port=0 test configuration is useful for integration tests, and the actual port is available from WebServerApplicationContext.

6. Tests and CI

java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class ApiTest { @LocalServerPort int port; }

Parallel test forks and parallel Gradle modules collide on fixed ports. Use random ports, or a per-worker offset such as server.port=${PORT:0}. When a container-based test leaves a listener behind after a failed run, the next run fails with the same error; testcontainers with random host ports avoids it. Use the curl reference to confirm which process answers on a port, and the CIDR calculator when binding to a specific subnet address.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Restarting without stopping. Two instances of the same jar, one started by systemd and one by hand, is the most common cause in production. Check the supervisor before killing anything.
  • Killing the wrong PID. A PID from an old log may now belong to another process. Always re-run ss and match the port, not the remembered number.
  • kill -9 first. It releases the port but skips shutdown hooks, leaving database connections and lock files behind.
  • Fixed ports in tests. @SpringBootTest without RANDOM_PORT plus parallel builds produces intermittent failures that look like flaky code.
  • Wrong port in the error. The message shows the port the kernel refused, not necessarily the one configured: a placeholder or environment variable may have resolved to the default.
  • Windows wording. The same failure reads Address already in use: JVM_Bind on Windows and bind on Linux; searches for either should include both.
  • IPv6-only hosts. A host with IPv6 disabled can fail to bind :: while the error mentions the port only. Check sysctl net.ipv6.conf.all.disable_ipv6.
  • Java 18 and later. The default charset and reflection changes do not affect binding, but container images that switched from JDK 8 to 17 often inherit a server.port from a base image environment variable, which changes which port conflicts.

Treat the port as a shared resource with an owner: find the owner with ss, decide whether to stop it or move, and prefer configuration over code so the next environment can choose a free port.

Official documentation: java.net.BindException and ServerSocket.

Official references

primary documentation

The Java documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.