Skip to content

Commit

Permalink
docs(blog): update nodemon post (#6475)
Browse files Browse the repository at this point in the history
  • Loading branch information
necatiozmen authored Nov 8, 2024
1 parent 1d0a069 commit 99bf53a
Showing 1 changed file with 144 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2024-04-30-nodemon/so
hide_table_of_contents: false
---

**This article was last updated on November 8, 2024 to include advanced Nodemon configurations and best practices for handling memory management in long-running processes.**

## Update: Enhanced Watch Mode in Node.js Version 22

One of the standout features in the latest release of Node.js, [version 22](https://nodejs.org/en/blog/announcements/v22-release-announce), is the improved watch mode. This feature is now considered stable, which means it's no longer experimental and can be relied upon for regular use.
Expand All @@ -24,6 +26,18 @@ As a developer, you know how tedious it is to restart the application every time

[Nodemon](https://nodemon.io/) watches the files in your project and instantly applies updates by restarting your app—no more manual resets. This has noticeably sped up my development process, making it smoother and more productive. It’s especially crucial in a fast-paced work environment where every second counts.

Steps we'll cover in this guide:

- [Installing Nodemon](#installing-nodemon)
- [Using Nodemon](#using-nodemon)
- [Advanced Configuration](#advanced-configuration)
- [Using Nodemon inside Docker Containers](#using-nodemon-inside-docker-containers)
- [Why Use Nodemon with Docker?](#why-use-nodemon-with-docker)
- [Basic Troubleshooting Tips](#basic-troubleshooting-tips)
- [Memory Leak Handling in Longer Running Nodemon Processes](#memory-leak-handling-in-longer-running-nodemon-processes)
- [Why memory leaks happen in long-running Nodemon processes](#why-memory-leaks-happen-in-long-running-nodemon-processes)
- [Prevention strategies for memory leaks using Nodemon](#prevention-strategies-for-memory-leaks-using-nodemon)

## Installing Nodemon

I just went through setting up Nodemon. You install it using npm, the Node.js package manager. Just open your terminal and type:
Expand Down Expand Up @@ -139,6 +153,136 @@ Here’s a breakdown:

These tweaks have made a noticeable difference in managing the development flow, especially in complex projects. I think implementing these could really streamline how we handle automatic restarts in our development process!

## Using Nodemon inside Docker Containers

I wanted to share this tutorial on how one integrates Nodemon with Docker, which turns out to be a game-changing setup when using Node.js applications running in Docker containers. This will allow it inside the Docker to, automatically restart the application in the container whenever changes are made to the code.

### Why Use Nodemon with Docker?

One of the most important advantages of developing in Docker containers is that we usually rebuild or restart the container for every change in the code, which really takes a lot of time. This step can be skipped by integrating Nodemon and letting Nodemon watch the changes in files and restart on its own inside the container.

**Setting up Nodemon with Docker**

To use Nodemon inside a Docker container, we will add Nodemon in our project and make some changes to the Docker configuration. Here is how you can do this step by step:

**Integrate Nodemon into the Project**

First, ensure Nodemon is installed within the project:

```bash
npm install --save-dev nodemon
```

**Dockerfile Update for Nodemon**
Next, in Dockerfile, set Nodemon as a command to start our app. Here’s a basic example:

```dockerfile
FROM node:14

# Set working directory
WORKDIR /app

# copy package.json and install dependencies
COPY package*.json ./
RUN npm install

# Copy the rest of the application
COPY . .

# Require Nodemon installation globally
RUN npm install -g nodemon

# Expose the required port
EXPOSURE 3000

# Nodemon as default run command
CMD ["nodemon", "app.js"]
```

**Create a Volume for Live Reloading**
In Docker, we will use volumes, so changes made to the files from our host machine reflect inside the container. By doing so, Nodemon will be able to detect real-time file change. Here’s an example docker-compose.yml file to set that up:

```yaml
version: "3"
services:
app:
build: .
volumes:
- .:/app # Mount current directory to /app in the container
- /app/node_modules # Avoids conflicts with the host node_modules
ports:
- "3000:3000"
command: nodemon app.js
```
**Running a Container**
Everything should now be set. Start your container:
```bash
docker-compose up
```

This setup will allow you to make changes to the code on your local machine, which are instantly reflected inside the container because of the volume mount; then Nodemon will detect these changes and restart the application automatically.

### Basic Troubleshooting Tips

- Permissions Issues: Sometimes on some systems, file permissions can be why Nodemon does not detect changes. You might want to change permissions or run Docker as root if this exists.
- Conflicting node_modules: Remember, while working with docker-compose.yml the application’s node_modules should not be part of the volume mount. If different, this causes conflict between the host and container.

## Memory Leak Handling in Longer Running Nodemon Processes

We would especially want to control the consumption of memory for applications that run continually through Nodemon during development. While Nodemon is great at watching and attempting to restart our application upon file changes, should it not be watched, a long-running Nodemon process can leak memory until eventually performance degrades and the app crashes. Following is how we could handle such a memory leak.

### Why memory leaks happen in long-running Nodemon processes

Memory leaks happen when, through our application, we keep references to data that is no longer needed and that prevents JavaScript’s garbage collector from freeing up the memory. In a development process that could run for a longer period of time, Nodemon might take up more and more memory over time due to repeated file changes, event listeners, or unoptimized code.

### Prevention strategies for memory leaks using Nodemon

**Memory Consumption Monitoring**

Use Node.js’s built-in memory monitoring to observe memory usage. Insert this into your code and log memory usage at regular intervals:

```javascript
setInterval(() => {
const memoryUsage = process.memoryUsage();
console.log(`Memory Usage: RSS ${memoryUsage.rss / 1024 / 1024} MB`);
}, 10000); // log memory usage every 10 seconds
```

**Limit Frequency of Restarts**

Not allowing the system time to clean up resources can cause a memory buildup with rapid restarts. To delay the restarts so the system can clear its memory, use the --delay flag inside of Nodemon:

```bash
nodemon --delay 2 app.js
```

**Watch PATHS Optimizations**

Avoid watching unnecessary files or directories to save on memory consumption. Example - you would likely want to exclude files like logs or static assets:

```
{
"watch": ["src"],
"ignore": ["logs/*", "public/*"]
}
```

**Identify and Optimize Code-related Leaks**

Identify unwanted listeners or event handlers not cleaned up. Usually, these are the most common sources of Node.js memory leaks. Use tools such as clinic.js or Chrome DevTools to trace heap snapshots and have detailed inspections of memory consumption.

**Periodic Restart**
If it is still not enough and memory consumption remains a problem, periodic restarts of Nodemon will clean up its memory usage, too. Use a process manager like pm2 to schedule this:

```bash
pm2 start nodemon --name "app" -- app.js --max-memory-restart 200M
```

These practices will help us to keep our development process smooth, even during long-running sessions with Nodemon. Feel free to let me know if you’d like to discuss setting up memory monitoring or provide a finger in the direction on how parts of this code could be optimized.

## Conclusion

As we wrap up discussing Nodemon, I wanted to share some common issues you might run into and how to troubleshoot them. Even though Nodemon simplifies our development by auto-restarting our apps, sometimes it might not work as expected.
Expand Down

0 comments on commit 99bf53a

Please sign in to comment.