How to get Java memory heap dump from pod in Kubernetes

Contents

Problem

Recently I had a problem where I needed to get the heap dump from a Java Spring Boot application running in a pod in a Kubernetes cluster.

This is not a trivial task but eventually I figured out how extract a heap dump from the pod.

Solution

The solution requires using kubectl exec to access the shell of a running container and then using jmap to extract the memory dump.

  1. Firstly get the name of the running pod by running:
kubectl get pods

You may need to use the -n <NAMESPACE> to get access to the pod.

Make a not of the pod name. For this example lets assume the pod name is called my-spring-pod

  1. Then run this command to get a shell into the container in the pod:
kubectl exec -ti pods/my-spring-pod -n <<ENTER NAMESPACE>> -- /bin/bash

This will open a shell to the container.

  1. Next change directory into the tmp folder:
cd /tmp
  1. Now we can generate the memory dump using jmap:
jmap -dump:format=b,file=snapshot.jmap 1

You can specify the name of the memory dump. I have set the name to snapshot.jmap for this example.

This will generate a memory dump with the name snapshot.jmap in the tmp folder in the container in the pod.

  1. Next exit out of the shell and the out of the cluster.
  2. Once you have disconnected from the shell, run this command to copy the snapshot.jmap memory dump out of the container and copy it to your local file system:
kubectl cp my-spring-pod:/tmp/snapshot.jmap /tmp/snapshot.jmap -n demo

This will copy the memory dump out of the container to the /tmp/ folder on your local machine.

You can use a tool like the Eclipse Memory Analyzer Tool to analyse the memory dump.

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.