Debug Gradle Application Running in Docker: Connection Error

Abstract: Resolve Gradle application connection errors during Docker debugging by configuring JVM JDWP flags to bind to 0.0.0.0 and mapping port 5005 in docker-compose.yml.

Created: 2026-07-27 by
Resolving connection errors when debugging a Gradle application in Docker requires aligning JVM debug flags, port mappings, and network configurations. The most common cause is the debugger binding to localhost inside the container or ports not being exposed correctly in docker-compose.yml. Ensuring -agentlib:jdwp uses 0.0.0.0 and mapping port 5005 explicitly allows your IDE to attach successfully.

Understanding the JDWP Configuration

The Java Debug Wire Protocol (JDWP) must be configured correctly within the running container for remote debugging to function. By default, many development environments bind the debugger listener to 127.0.0.1, which restricts access to only processes running inside the same container namespace. When you attempt to connect from your host machine’s IDE, the connection is refused because the port is not reachable from outside the container. To fix this, you need to ensure that the JVM listens on all available network interfaces. This is achieved by adding specific arguments to the JVM options passed to the Gradle build or the runtime command. The critical flag is -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005. Notice the use of *:5005 instead of just 5005 or localhost:5005. The asterisk tells the JVM to bind to 0.0.0.0, making the debug port accessible from any IP address, including the host machine. If you are using Spring Boot, the configuration might look slightly different, often involving environment variables like DEBUG_PORT. However, for standard Gradle applications, modifying the jvmArgs in your build.gradle file or the Dockerfile ENTRYPOINT is the standard approach. Ensure that the suspend parameter is set to n if you want the application to start immediately without waiting for the debugger to attach, which is crucial for testing startup issues.

Verifying Docker Compose Port Mappings

Even with correct JVM arguments, the container will not expose the debug port to the host unless it is explicitly mapped in your docker-compose.yml file. A frequent mistake is exposing the application port (e.g., 8080) but forgetting to map the debug port (5005). You must add a separate entry in the ports section of your service definition. Here is an example of how the configuration should look:
services:
  app:
    image: my-gradle-app:latest
    ports:
      - "8080:8080"
      - "5005:5005"
    environment:
      - DEBUG=true
The format host_port:container_port ensures that traffic directed to port 5005 on your local machine is forwarded to port 5005 inside the container. If you omit the second line, your IDE will fail to connect regardless of how well the JVM is configured. Additionally, verify that no firewall rules on your host machine are blocking incoming connections on port 5005, although this is less common in local development environments. For more complex setups involving multiple services, such as those described in our guide on Microservice Health Check Instance Docker, ensure that the container networking mode allows inter-container communication if the debugger is attached from another container rather than the host.

Checking Network Connectivity and Hosts File

Sometimes the issue lies not in the configuration but in how the container resolves its own hostname. If the JVM binds to the container’s hostname instead of 0.0.0.0, external connections may fail. You can verify this by executing a shell inside the running container and checking the listening ports. Use the following command to inspect open ports:
docker exec -it <container_id> netstat -tlnp | grep 5005
Or, if netstat is unavailable, try:
docker exec -it <container_id> ss -tlnp | grep 5005
You should see the port listed as 0.0.0.0:5005 or *:5005. If it shows 127.0.0.1:5005, the JVM configuration is still incorrect. Also, check the /etc/hosts file inside the container to ensure there are no conflicting entries that might redirect localhost traffic unexpectedly. In some Docker Desktop configurations, changing the network_mode to host can bypass NAT issues, but this is generally discouraged for multi-service architectures due to port conflicts. If you encounter issues where the debugger attaches but stops working after a few minutes, consider checking for idle timeouts in your IDE settings. Our article on How to always force 'Run Without Debugging' to Output to the Debug Console? touches on IDE behavior that might affect session stability, though it focuses on output redirection rather than connection drops.

Gradle Build Script Adjustments

To make debugging easier during development, you can create a custom Gradle task that launches the application with debug flags enabled. This avoids manually editing environment variables every time you restart the container. Define a new task in your build.gradle file:
task runWithDebug(type: JavaExec) {
    group = "application"
    mainClass = "com.example.Application"
    jvmArgs = [
        "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005",
        "-Dspring.profiles.active=dev"
    ]
}
Then, modify your Dockerfile to use this task or pass these arguments via environment variables that the application reads at startup. This ensures consistency between local runs and containerized runs. Remember to exclude these debug flags from production builds to avoid performance overhead and security risks.

Frequently Asked Questions

Why does the debugger disconnect immediately after attaching?

This usually happens if the JVM is configured with suspend=y and the application crashes before the debugger connects. Set suspend=n to allow the app to start independently. Additionally, check for unhandled exceptions in the logs that might terminate the process instantly.

Can I use a different port for debugging instead of 5005?

Yes, you can change the port by modifying the address parameter in the -agentlib:jdwp flag, such as address=*:9009. Ensure you also update the port mapping in docker-compose.yml to match the new port number on both the host and container sides.

How do I debug a Gradle wrapper inside Docker?

You cannot directly debug the Gradle wrapper execution itself through the JVM debug agent easily. Instead, focus on debugging the application code launched by Gradle. Ensure the application process, not the Gradle daemon, has the debug flags enabled in its JVM arguments.

What if the container is behind a reverse proxy?

Reverse proxies typically handle HTTP traffic, not raw socket connections used by JDWP. You must bypass the proxy for the debug port or configure the proxy to support TCP forwarding. Directly mapping the debug port in Docker Compose is the recommended approach for local debugging.

Does Docker Desktop on Windows handle port 5005 differently?

Windows Docker Desktop uses a Linux VM internally, so port mappings work similarly to Linux. However, ensure that Windows Firewall is not blocking inbound connections on port 5005. You may need to create an inbound rule allowing traffic on this port for public and private networks.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More