DEV Community

loading...
Cover image for Kubernetes for Java Developers - Debug Application

Kubernetes for Java Developers - Debug Application

sandrogiacom profile image Sandro Giacomozzi ・2 min read

Debug application

At this point, we deployed our application within a local cluster. But now we have a problem. How do I debug my application that is inside the docker that is inside the kubernetes that is inside a virtual machine?

Prepare to debug

In this case, we will use a remote Java debug.

First step:

Prepare your Dockerfile:

FROM openjdk:11.0.3-jdk-slim
RUN mkdir /usr/myapp
COPY target/java-kubernetes.jar /usr/myapp/app.jar
WORKDIR /usr/myapp
EXPOSE 8080
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -jar app.jar" ]

This ENTRYPOINT allows you to pass options to the java through $JAVA_OPTS environment variable.

Second step:

Changing app-configmap.yaml file to fill $JAVA_OPTS.

JAVA_OPTS: "-agentlib:jdwp=transport=dt_socket,address=*:5005,server=y,suspend=n -Xms256m -Xmx512m -XX:MaxMetaspaceSize=128m"

Third step:

Building and deploy app:

mvn clean install
eval $(minikube -p dev.to docker-env) && docker build --force-rm -t java-k8s .
kubectl apply -f kubernetes/app/

Fourth step:

Exposing debug port to localhost:

Get pods:

kubectl get pods -n dev-to

NAME                     READY   STATUS    RESTARTS   AGE
myapp-7796bc89bf-h2f82   1/1     Running   0          3h3m

Expose pod 5005 port:

kubectl port-forward -n dev-to myapp-7796bc89bf-h2f82 5005:5005
Forwarding from 127.0.0.1:5005 -> 5005
Forwarding from [::1]:5005 -> 5005

Change your pod name as necessary.

Create a remote debug on your IDE:

On IntelliJ, go to Run/Debug Configurations.

  • Add new remote configuration like this:

After that, run the configuration. You should see the message below:

Connected to the target VM, address: 'localhost:5005', transport: 'socket'

Check if works:

Now, you can set a breakpoint in the HelloController.


minikube -p dev.to service -n dev-to myapp --url
http://192.168.99.100:32301
curl http://192.168.99.100:32301/hello

Conclusion

In this part, we learned about how to debug application inside a local kubernetes cluster.

In the next part, we will see some good practices and how to access application with friendly URL using Ingress.

See you soon!

Discussion (0)

pic
Editor guide