Master Automatic Restarts for Node.js: From Nodemon to PM2 and Docker
Learn how to ensure your Node.js applications stay alive by configuring automatic restarts for both development and production environments, using tools like Nodemon, PM2, Docker restart policies, systemd, and advanced PM2 features such as clustering, log management, and crash handling.
Running a Node.js app in production or during development can be frustrating when it crashes and doesn't automatically restart, requiring manual intervention.
This can be caused by a small bug, server overload, or an uncaught exception—without an automatic restart feature, your app becomes unreliable and users are affected.
Good news: there is a clean solution—today we'll show you how to set up automatic restarts for your Node.js app like a pro.
Why Node.js Needs Automatic Restart
Node.js is powerful but doesn't provide automatic restart out of the box.
Imagine you've deployed your backend API, but a filesystem error or network failure causes it to crash. Without automatic restart, the service stays offline until someone intervenes.
Automatic restart solves these problems:
Keep your app running 24/7
Recover from crashes and unexpected shutdowns
Increase reliability without manual actions
Improve development experience with hot‑loading
Now let's explore how to implement this efficiently.
Two Scenarios: Development vs Production
Automatic restart is crucial in two main use cases:
During development: you want the app to restart automatically when code changes, saving time and boosting productivity.
In production: you want the app to recover automatically from crashes or memory leaks.
Each case requires a slightly different approach.
1. Automatic Restart in Development: Using nodemon
What is Nodemon?
Nodemon is a development tool that watches file changes in your Node.js app and automatically restarts the app when files are modified. It's ideal for development workflows.
How to Install Nodemon
You can install it globally or as a dev dependency. npm install -g nodemon Or:
npm install --save-dev nodemonModify Your package.json
Update the scripts section to use nodemon:
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
}Now run: npm run dev Each time you change a file, nodemon will automatically restart your app.
Custom File Watching
Want to watch specific folders or ignore others? Create a nodemon.json in the project root:
{
"watch": ["src"],
"ignore": ["node_modules", "logs"],
"ext": "js,json"
}This gives you fine‑grained control over what triggers a restart.
2. Automatic Restart in Production: Using PM2
What is PM2?
PM2 is a production‑grade Node.js process manager. It not only restarts your app automatically after a crash but also:
Manages logs
Monitors memory usage
Supports clustering
Enables zero‑downtime deployments
Install PM2
Install globally:
npm install pm2 -gStart Your App with PM2
Assuming your entry file is index.js: pm2 start index.js PM2 now monitors your app and restarts it if it crashes or exits.
Auto‑Start on System Boot
You probably don't want to manually start PM2 after every server reboot.
Run: pm2 startup It will output a command similar to:
sudo env PATH=$PATH:/home/ubuntu/.nvm/versions/node/v18.17.1/bin pm2 startup systemd -u ubuntu --hp /home/ubuntuCopy and paste that command, then save the current process list: pm2 save Now your app will start automatically after a server reboot.
Smart Crash and Restart Management
If you don't want the app to keep restarting in a severe error loop, PM2 lets you control this:
pm2 start index.js --max-restarts 5 --restart-delay 3000This means:
Try to restart a maximum of 5 times
Wait 3 seconds between each restart
Managing Application Logs
When an app crashes, logs are essential. PM2 organizes logs for you: pm2 logs Or for a specific app: pm2 logs my-app Log files are usually stored in ~/.pm2/logs/ and include: my-app-out.log – standard output my-app-error.log – error output only
To clear logs:
pm2 flushRestart on File Changes in Production
By default, production apps shouldn't restart on every file change, but during testing or hot‑loading you can enable it: pm2 start index.js --watch Be careful using this in production unless you have advanced hot‑loading logic.
You can also ignore certain paths:
pm2 start index.js --watch --ignore-watch="node_modules logs"Monitoring and Dashboards
PM2 provides both CLI and web‑based monitoring tools.
CLI: pm2 monit Web dashboard (PM2 Plus) or the open‑source Keymetrics dashboard:
pm2 plus pm2 link [public-key] [secret-key]These are useful for remote monitoring and alerts.
Advanced PM2 Tips for Real‑World Apps
Use an ecosystem.config.js to manage multiple apps or processes:
module.exports = {
apps: [
{
name: "api",
script: "index.js",
watch: true,
env: {
NODE_ENV: "development"
},
env_production: {
NODE_ENV: "production"
}
}
]
}Start with: pm2 start ecosystem.config.js Use cron_restart to periodically restart the app (prevent memory leaks): cron_restart: "0 0 * * *" Leverage clustering to utilize multiple CPU cores: pm2 start index.js -i max This launches as many instances as you have CPU cores.
If You Don't Want to Use PM2
Other options include:
Forever : another Node.js process manager
Docker + restart policies : use Docker's native restart options
systemd or Supervisor : native OS process managers
For example, a systemd unit might look like:
[Unit]
Description=Node.js App
After=network.target
[Service]
ExecStart=/usr/bin/node /home/user/app/index.js
Restart=always
User=ubuntu
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.targetSave as /etc/systemd/system/my-node-app.service and enable:
sudo systemctl daemon-reexec
sudo systemctl enable my-node-app
sudo systemctl start my-node-appUsing Docker to Implement Restarts in Containerized Environments
If your Node.js app runs in Docker, ensure you configure a restart policy: docker run --restart=always Available options include no, on-failure, always, and unless-stopped. This is crucial for self‑healing containers.
Final Checklist for Automatic Restart Setup
Install and configure nodemon for development.
Use pm2 for process management in production.
Enable system boot with pm2 startup and pm2 save.
Monitor logs with pm2 logs.
Apply restart policies to ensure long‑term stability.
Extra Tips: Improving Application Stability Beyond Restarts
Remember, automatic restarts aren't a cure‑all.
If your app crashes frequently, focus on:
Writing proper try/catch around critical logic.
Handling unhandled rejections:
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled Rejection:", promise, "reason:", reason);
});Managing memory leaks
Rate‑limiting user input
Isolating dependencies (e.g., databases or third‑party APIs)
A stable program + automatic restart = rock‑solid production setup.
Conclusion
Automatic restart is essential for Node.js in both development and production.
Tools like nodemon, PM2, Docker, and systemd are not just conveniences; they are key building blocks for scalable Node.js infrastructure.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
