How to debug a nodeJS application inside a Kubernetes Pod?

8/9/2019

Pretty much the title of the question.

I am working with an Ubuntu system that has a k8s deployment with multiple nodes and with multiple pods that run Docker containers. A few of the pods are nodeJS microservices which run the following command at initiation:

node app.js

Sometimes I need to debug the microservice by adding logs, changing logic inside, etc.

Working with the same microservices in Windows I could just change the source code and restart the node.exe process. How would I achieve doing the same in Linux with a Kubernetes deployment?

I attempted to run a shell:

user@node1:~$ kubectl exec my-microservice-XXXX -it -- sh

Change source code and save: nano app.js

Find the node process: ps aux

PID   USER     TIME  COMMAND
    1 root      0:00 npm
   22 root      0:00 npm
   42 root      0:27 node --max-http-header-size=65000 app.js

Then send SIGTERM to PID 42:

kill SIGTERM 42

And this results in me being booted out of the pod:

/usr/src/app # kill SIGTERM 42
sh: invalid number 'SIGTERM'
/usr/src/app # command terminated with exit code 137
test@node1:~$

And a new pod starts automatically:

my-microservice-XXXX                       0/1     Completed   1          19h
my-microservice-XXXX                       1/1     Running     2          19h
-- Kobbi Gal
docker
kubernetes
node.js

2 Answers

2/3/2020

With the following two steps, you can debug a Node app running inside a Docker container in a kubernetes Pod:

  1. Log into the container and run the Node app in the debug mode:
kubectl exec -it <pod-name> bash
node --inspect-brk index.js
  1. Forward connections to a local port to a port on the Pod
kubectl port-forward <pod-name> 9229

Note: 9229 is the default port number that the debugger listens on, and you don't need to expose this port in your Kubernetes configuration yaml file.

That is it.

Now you can open you Chrome browser with address chrome://inspect, click the remote target, and start debugging.

-- Yuci
Source: StackOverflow

8/9/2019

This is not possible in Kubernetes as a straight forward way, as we do not manage the container (Creation, termination, etc). This is done by Kubernetes and hence the process is ephemeral.

If you don't want to lose your changes on container restart, then you can use volume mount of the directory where you're making the changes. (This completely defeats the purpose of docker containerisation and a not a recommended for production (any) environment to store the code in volume).

-- Sagar Chilukuri
Source: StackOverflow