How to Develop and Debug Node.js Applications on Kubernetes
Tags: kubernetes, node, cloudnative, docker
Published: 2020-09-24 08:18:04

[Kubernetes](https://kubernetes.io/) is an open-source project for automating deployment, scaling, and management of containers. It has rapidly become the standard to run production workloads and the community around it is just great!

But developing on Kubernetes presents some challenges. The typical development workflow looks like this: write code, build a Docker image, push it to the registry, redeploy, validate your changes and repeat. This flow is not only slow, but it also prevents us from benefiting from standard features of the Node.js ecosystem such as application hot-reloaders or debuggers.

[Okteto](https://github.com/okteto/okteto) was created to solve this problem. On this blog post, we will show you how Okteto improves the developer experience in Kubernetes for Node.js developers. You will be able to take full advantage of tools like `nodemon`, dependency caching or IDE debuggers while developing your application directly on Kubernetes.

<!-- more -->
## Step 1: Deploy the Node.js Sample App

Get a local version of the Node.js Sample App by executing the following commands:

```console
$ git clone https://github.com/okteto/node-getting-started
$ cd node-getting-started
```

The `k8s.yml` file contains the [Kubernetes manifests](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) to deploy the Node.js Sample App. Run the application by executing:

> You can deploy to your own Kubernetes cluster or give [Okteto Cloud](https://cloud.okteto.com/) a try. Okteto Cloud is a development platform for Kubernetes applications. Sign up today to get a free developer account with 4 CPUs and 8GB of RAM.

```console
$ kubectl apply -f k8s.yml
```

```console
deployment.apps "hello-world" created
service "hello-world" created
```

This is cool! You typed one command and a dev version of your application just runs 😎.

## Step 2: Install the Okteto CLI

The [Okteto CLI](https://github.com/okteto/okteto) is an open-source project that lets you develop your applications directly on Kubernetes while taking advantage of well-known local tooling. We will use it to speed up our development cycle instead of using the typical development workflow based on building docker images and redeploying containers.

Install the Okteto CLI:

### MacOS / Linux
```console
$ curl https://get.okteto.com -sSfL | sh
```
</details>

### Windows
Download https://downloads.okteto.com/cli/okteto.exe and add it to your `$PATH`.

## Step 3: Create your okteto manifest

To start developing on the Node.js Sample App you first need to create an okteto manifest.
With the Node.js Sample App deployed, run the following command to create your [okteto manifest](/docs/reference/manifest):

```console
$ okteto init
```

```console
This command walks you through creating an okteto manifest.
It only covers the most common items, and tries to guess sensible defaults.
See https://okteto.com/docs/reference/manifest for the official documentation about the okteto manifest.
Use the arrow keys to navigate: ↓ ↑ → ←
Select the deployment you want to develop:
  ▸ hello-world
    Use default values
```

The `okteto init` command will scan the available deployments in your Kubernetes namespace, and ask you to pick one.
Select the `hello-world` deployment. It's the one we deployed on the previous step.

```console
 ✓  hello-world
 ✓  Deployment 'hello-world' successfully analyzed
 ✓  okteto manifest (okteto.yml) created
 i  Run 'okteto up' to activate your development container
```

The `okteto init` command creates the following `okteto.yml` file:

```yaml
name: hello-world
image: okteto/node:12
command: bash
sync:
  - .:/usr/src/app
forward:
  - 3000:3000
  - 9229:9229
```

This file defines how to activate a development container for the Node.js Sample App:

- `name`: the name of the Kubernetes deployment you want to put on development mode.
- `image`: the image used by the development container.
- `command`: the start command of the development container. 
- `sync`: the folders that will be synchronized between your local machine and the development container. 
- `forward`: a list of ports to forward from your development container.

Also, the `okteto init` command creates a `.stignore` file to indicate which files shouldn't be synchronized to your development container.
This is useful to avoid synchronizing binaries, build artifacts, git metadata or dependencies like `node_modules`.

## Step 4: Activate your development container

Next, execute the following command to activate your development container:

```console
$ okteto up
```

```console
 ✓  Development container activated
 ✓  Files synchronized
    Namespace: default
    Name:      hello-world
    Forward:   3000 -> 3000
               9229 -> 9229

Welcome to your development container. Happy coding!
default:hello-world app>
```

Working in your development container is the same as working on your local machine.
Start by installing your dependencies:

```console
default:hello-world app> yarn install
```

```console
yarn install v1.22.4
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
Done in 2.09s.
```

Start the application in hot-reload mode by running the following command:

```console
default:hello-world app> nodemon index.js
```

```console
yarn run v1.22.4
$ nodemon index.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Starting hello-world server...
```

Okteto automatically forwards port `3000` from your local computer to the development container, making it accessible via `localhost`. Test your application by running the command below in a local shell:

```console
$ curl localhost:3000
```

```console
Hello world!
```

## Step 5: Develop directly in Kubernetes

Open the `index.js` file in your favorite local IDE and modify the response message on line 5 to be *Hello world from the cluster!*. Save your changes.

```javascript
  res.send('Hello world from the cluster!');
```

Okteto will synchronize your changes to your development container.
Take a look at the development container shell and notice how the changes are detected by `nodemon` automatically hot reloaded.

```console
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Starting hello-world server...
```

Test your application by running the command below in a local shell:

```console
$ curl localhost:3000
```

```console
Hello world from the cluster!
```

Cool! Your code changes were instantly applied to Kubernetes. No commit, build or push required 😎!

## Step 6: Debug directly in Kubernetes

Okteto enables you to debug your applications directly from your favorite IDE.
Let's take a look at how that works in VS Code, one of the most popular IDEs for Node development.
If you haven't done it yet, install the Node.js extension available from Visual Studio marketplace.

Cancel the execution of `nodemon index.js` from the development container shell by pressing `ctrl + c`.
Rerun your application in debug mode:

```console
default:hello-world app> node --inspect-brk=0.0.0.0:9229 index.js
```

```console
Debugger listening on ws://0.0.0.0:9229/73d8d793-b0c3-4310-86ee-3a42938a5df1
For help, see: https://nodejs.org/en/docs/inspector
```

Open the _Debug_ extension and run the *Connect to okteto* debug configuration (or press the F5 shortcut):

```json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Connect to okteto",
            "type": "node",
            "request": "attach",
            "address": "localhost",
            "port": 9229,
            "localRoot": "${workspaceFolder}",
            "remoteRoot": "/usr/src/app",
            "skipFiles": [
                "<node_internals>/**"
            ]
        },
    ]
}
```

Add a breakpoint on `index.js`, line 5. Call your application again by running the command below from a local shell.

```console
$ curl localhost:3000
```

The execution will halt at your breakpoint. You can then inspect the request, the available variables, etc...

![VS Code Debug View](https://dev-to-uploads.s3.amazonaws.com/i/8j84qi3oohwy0rcp8otc.png)

Your code is running in Kubernetes, but you can debug it from your local machine without any extra services or tools.
Pretty cool no? 😉

# Conclusions

Kubernetes has the potential to be a great development platform, providing replicable, resource-efficient and production-like development environments. We have shown you how to use [Okteto](https://github.com/okteto/okteto) to create a development workflow that also lets you take advantage of features like hot reloaders or debuggers while developing your application directly on Kubernetes. 

Visit our [website](https://okteto.com/) to know more about how to improve your team developer productivity with Okteto. Follow us [on Twitter](https://twitter.com/oktetohq) and join our [#okteto](https://kubernetes.slack.com/messages/CM1QMQGS0/) channel in the [Kubernetes community Slack](http://slack.k8s.io/) to share your feedback with our community.