Skip to content

Instantly share code, notes, and snippets.

@rmichela
Created December 10, 2025 00:27
Show Gist options
  • Select an option

  • Save rmichela/69a3cfd6b815e7686f00a6143a915b65 to your computer and use it in GitHub Desktop.

Select an option

Save rmichela/69a3cfd6b815e7686f00a6143a915b65 to your computer and use it in GitHub Desktop.
k8s-java-dump.sh
#! /bin/sh
set -e
# 1. Collect kubernetes namespace and pod name from the user into variables
while getopts "n:p:" opt; do
case $opt in
n) NAMESPACE="$OPTARG" ;;
p) POD="$OPTARG" ;;
*) echo "Usage: $0 -n <namespace> -p <pod>"; exit 1 ;;
esac
done
if [ -z "$NAMESPACE" ] || [ -z "$POD" ]; then
echo "Usage: $0 -n <namespace> -p <pod>"
exit 1
fi
# 2. Execute jcmd to get the process id of the first running java process in the pod
# Extract the PID from the numeric ID from the first line of the response into a variable
PID=$(kubectl exec -n "$NAMESPACE" "$POD" -- java -m jdk.jcmd/sun.tools.jcmd.JCmd | awk 'NR==1 {print $1}')
echo "🆔 Found java executable at PID $PID"
# 3. Extract the container's home directory
CONTAINER_HOME=$(kubectl exec -n "$NAMESPACE" "$POD" -- sh -c 'echo $HOME')
echo "🏠 Located container home $CONTAINER_HOME"
# 4. Using the process ID, dump a heap file
echo "🧠 Dumping java memory..."
kubectl exec -n "$NAMESPACE" "$POD" -- rm -f "$CONTAINER_HOME"/heap.bin
kubectl exec -n "$NAMESPACE" "$POD" -- java -m jdk.jcmd/sun.tools.jmap.JMap -dump:live,format=b,file="$CONTAINER_HOME"/heap.bin "$PID"
# 5. Download the heap dump locally
echo "⬇️ Downloading dump file..."
rm -f ./heap.bin
kubectl exec -n "$NAMESPACE" "$POD" -- base64 "$CONTAINER_HOME"/heap.bin | base64 -d > ./heap.bin
echo "✅ Download complete"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment