Keywords: Node.js | Linux | Background Process | SSH | Process Management
Abstract: This comprehensive article explores multiple methods for keeping Node.js processes running persistently on Linux servers through SSH connections. From basic nohup commands to screen/tmux session management, and professional process monitoring tools like pm2, it thoroughly analyzes the advantages, disadvantages, and applicable scenarios of various solutions. The article also delves into the debate about whether to run Node.js directly in production environments and provides best practice recommendations based on system-level monitoring.
Problem Background and Challenges
In Linux server environments, developers frequently need to deploy and manage Node.js applications through SSH connections. A common issue arises: when SSH connections are terminated, background processes started with the node server.js & command also die. This situation is particularly evident in SSH clients like Putty, where even with basic background execution using the & symbol, processes cannot survive terminal disconnections.
Basic Solution: The nohup Command
The nohup (no hang up) command represents the most fundamental approach to solving this problem. This command is specifically designed to allow processes to continue running after terminal disconnection. The basic usage is as follows:
nohup node server.js &
However, simple nohup commands may not fully meet requirements, especially when handling standard output and error output. A more complete command format should be:
nohup node server.js > /dev/null 2>&1 &
Here's a breakdown of each component:
nohup: Ensures the process isn't terminated when the terminal disconnects> /dev/null: Redirects standard output to the null device, preventing output file creation2>&1: Redirects standard error output to standard output&: Runs the process in the background
If error logging is required, replace the error redirection with 2>/tmp/myLog, which saves all error messages to the specified file.
Advanced Session Management: screen and tmux
For scenarios requiring interactive operations, screen and tmux provide more robust solutions. These tools create persistent terminal sessions where processes continue running even after SSH connections are terminated.
Basic workflow using screen:
# Start a new screen session
screen
# Launch Node.js application within the session
node server.js
# Detach from session (process continues running)
Ctrl+a d
# Reattach to session
screen -r
tmux, as a modern alternative to screen, offers richer features and better user experience. The usage is similar:
# Start tmux session
tmux
# Run application
node server.js
# Detach from session
Ctrl+b d
# Reattach
tmux attach
Professional Process Management: PM2 Tool
In production environments, professional process managers like pm2 provide comprehensive solutions. PM2 not only keeps processes running but also offers advanced features including process monitoring, automatic restart, and load balancing.
Basic usage:
# Install pm2
npm install -g pm2
# Start application
pm2 start server.js
# Check running status
pm2 status
# View logs
pm2 logs
# Stop application
pm2 stop server.js
Key advantages of PM2 include:
- Automatic restart: Automatically reboots applications when they crash
- Cluster mode: Supports multi-process load balancing
- Log management: Unified log recording and rotation
- Monitoring capabilities: Real-time monitoring of application performance and resource usage
Production Environment Considerations
Regarding whether to run Node.js processes directly, different perspectives exist within the industry. While traditional advice suggests "never run Node.js directly in production," this requires evaluation based on specific scenarios.
Main risks of direct Node.js execution:
- Single point of failure: One unhandled error can crash the entire application
- Lack of monitoring: No automatic restart or health check mechanisms
- Resource management: Inability to effectively utilize multi-core CPUs
However, in containerized environments (such as Docker, Kubernetes), direct Node.js execution may be acceptable because container orchestration systems inherently provide process monitoring and restart capabilities. In such cases, containers automatically restart when applications crash, ensuring service availability.
System-Level Solution: systemd
For environments with Linux system control, systemd provides operating system-level service management. By creating systemd service unit files, Node.js applications can run as system services with automatic startup, restart, and monitoring capabilities.
Example service file:
[Unit]
Description=Node.js Application
After=network.target
[Service]
Type=simple
User=nodeuser
WorkingDirectory=/path/to/application
ExecStart=/usr/bin/node server.js
Restart=on-failure
[Install]
WantedBy=multi-user.target
Best Practices Summary
Based on different usage scenarios, the following solutions are recommended:
- Development Environment: Use
screenortmuxfor session management - Simple Production Environment: Use
pm2for process management - Containerized Environment: Leverage container orchestration system monitoring capabilities
- Traditional Server: Use
systemdservice management - Quick Testing: Use
nohupfor simple background execution
Regardless of the chosen solution, ensuring application stability and recoverability is crucial. Additionally, proper error handling and logging mechanisms are essential factors for maintaining healthy application operation.