When working with Spring Boot applications in IntelliJ IDEA, you might have encountered an issue where port 8080 (or another port) remains occupied even after stopping the application that you are working on. This is often caused by Gradle's daemon threads, which continue running in the background and do not release the port properly. I have encountered this issue several times and it's annoying to begin with.
Source: Dall-E
The Problem
Spring Boot applications typically run on port 8080 by default unless otherwise you have a different port configured in your app configs yaml/properties file.
server.port=8080
When you stop your application in IntelliJ IDEA, you may expect the port to be freed. However, in some cases, the Gradle daemon continues running background processes, keeping the port occupied. This is a problem that you do not want to face if you have a 9:00AM demo and you believe you stopped the application before leaving your desk last evening.
If you try to restart the application, you might see an error like
Application failed to start: Port 8080 is already in use
At this point, your only option is to close the port manually so you can reuse it and free-up the memory it is taking while keeping your application running in the background.
Manually Closing Port 8080 on Windows 11
Open the command prompt or powershell, and use following command
netstat -ano | findstr :8080
this should give you something closely matching to following response.
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 450121
That 450121 is the process id in windows that is keeping your port 8080 busy. You can terminate the windows process with following taskkill command
taskkill /PID 450121 /F
Verify the process was killed by searching for the PID again
netstat -ano | findstr :8080
Manually Closing Port 8080 on Linux/iOS(Macbook)
In the shell, find the process using the port 8080 using following command
lsof -i :8080
or
netstat -nlp | grep :8080
You should be able to see something similar to following in response
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 450121/java
Kill the process
kill -9 450121
and verify its closed successfully by using previous commands.
Configuring Gradle to Prevent Port Locking
To prevent Gradle from keeping daemon threads running after stopping the application, modify the settings:
1. Disable Gradle Daemon in gradle.properties
usually found in ~/.gradle/ or in the project’s gradle/ folder, open the file named gradle.properties and find following configuration, if you can not find the configuration, you can add it at the bottom of the file.
gradle.daemon=false
2. Stop Gradle Daemon Manually
Theoretically using "gradlew --stop" can kill all daemons, but i did not have much success with it:
./gradlew --stop
3. Run Gradle in Non-Daemon Mode
Instead of disabling the daemon, you can start your application in non-daemon mode using:
./gradlew bootRun --no-daemon