
Imagine you have deployed your Node.js application to a production server. Everything is working perfectly. Your APIs are responding, your database is connected, and users can access your website without any issues.
A few days later, you restart the server to install security updates. The server comes back online, but your website does not work. Nginx is running, the server is accessible, but your Node.js application is no longer responding.
You connect through SSH, navigate to your project directory, and manually start the application. Suddenly, everything starts working again.
This is a common problem when deploying applications on a VPS or cloud server. The application was started manually, so it was not configured to start automatically when the operating system booted.
For development, running a command such as npm start in a terminal might be enough. In production, however, you need a more reliable setup.
Your application should start when the server boots, recover when the application process crashes, and run without requiring you to open an SSH session.
In this guide, we will explore how to configure automatic application restarts using PM2, systemd, and Docker. We will also cover environment variables, startup dependencies, common mistakes, and how to verify that everything works after a reboot.
1. Why Doesn't an Application Restart Automatically?
Before configuring automatic startup, it helps to understand what happens when a Linux server reboots.
Suppose you start your Node.js application using:
node server.jsOr perhaps you use:
npm startThe application runs as a process associated with your current shell session.
When the server shuts down, the operating system terminates its running processes. After the server starts again, Linux does not automatically know which application commands you previously executed.
You must configure a service manager or process manager to start your application again.
A typical production setup looks like this:
Linux Server Boots
|
v
Operating System Starts
|
v
Service Manager Starts
PM2 / systemd
|
v
Node.js Application
|
v
Application Becomes Ready
|
v
Nginx Proxies RequestsThe exact order depends on your configuration. For example, Nginx may start before the application is ready, which can temporarily produce a 502 Bad Gateway response.
The important point is that starting a server and starting your application are two different things.
Your VPS can be running normally while your application process is completely stopped.
2. Choose the Right Method for Automatic Restarts
There are several ways to manage an application's lifecycle on a production server.
The most common options are:
Method | Best For | Main Advantage |
|---|---|---|
PM2 | Node.js applications | Process monitoring, crash recovery, logs, and startup configuration |
systemd | Linux services and applications | Native service management with detailed restart controls |
Docker restart policies | Containerized applications | Automatically restarts containers according to configured policies |
Kubernetes | Containerized applications running in a cluster | Supports orchestration, health checks, and workload recovery |
You do not need to use every method.
For a straightforward Node.js application running on an Ubuntu VPS, PM2 is often convenient. If you prefer managing the application as a native Linux service, systemd is a strong option.
If your application already runs inside Docker, container restart policies may be the simplest solution.
Let's look at each approach.
3. Method One: Automatically Restart a Node.js Application Using PM2
PM2 is a process manager designed for Node.js applications. It can keep applications running, restart them after crashes, manage logs, and configure startup behavior.
For developers working with Express, NestJS, or other Node.js frameworks, PM2 is a practical choice.
Step 1: Install PM2
First, make sure Node.js and npm are installed.
Check their versions:
node -v
npm -vInstall PM2 globally:
npm install -g pm2Verify the installation:
pm2 -vIf your Node.js installation uses a version manager such as NVM, make sure PM2 is installed and available under the same user account that will run your application.
This matters because PM2 maintains its process list and startup configuration in the context of the user running it.
Step 2: Navigate to Your Project
Move into your application directory:
cd /var/www/myappReplace /var/www/myapp with the actual path to your project.
Install the production dependencies if they have not already been installed:
npm ci --omit=devThis command is appropriate when your project has a valid package-lock.json and all dependencies required to run the application are included in the production dependency set.
If your project requires a build step, such as a TypeScript compilation or a Next.js production build, complete that step as part of your deployment process.
For example, a NestJS application may need to be compiled before it can run:
npm ci
npm run build
npm prune --omit=devRun the build process using the instructions appropriate for your project.
Step 3: Start the Application With PM2
For a basic Node.js application, you can start the server using:
pm2 start server.js --name myappIf your entry point is index.js, use:
pm2 start index.js --name myappFor a NestJS application that runs its compiled output from dist/main.js, you might use:
pm2 start dist/main.js --name myappThe entry point depends on how your project is structured.
If your application normally starts through an npm script, PM2 can also run that command:
pm2 start npm --name myapp -- startThis is useful when your package.json contains a suitable production start script.
For example:
{
"scripts": {
"start": "node server.js"
}
}After starting the application, inspect its status:
pm2 statusYou should see your application listed with its current status.
Step 4: Configure PM2 to Start After a Reboot
Starting an application with PM2 does not, by itself, guarantee that it will return after a server reboot.
You also need to configure PM2's startup integration.
Run:
pm2 startupPM2 will display instructions for configuring startup on your system. Depending on your operating system and installation, it may provide a command that needs to be executed with elevated privileges.
Copy and run the exact command PM2 provides.
Do not assume that the generated command will be identical on every server.
This step typically configures a system service that launches the PM2 daemon when the operating system starts.
Step 5: Save the Application Process List
This step is important and frequently overlooked.
After starting your application, run:
pm2 savePM2 saves the current process list so it can restore the managed applications when its startup mechanism runs.
The basic sequence is:
pm2 start server.js --name myapp
pm2 startup
pm2 saveRemember that pm2 startup may display an additional command that you must execute before the setup is complete.
Also, pm2 save records the current process list. If you add or remove applications later, update the saved list when appropriate.
Step 6: Verify the Configuration
Check the application status:
pm2 statusInspect recent logs:
pm2 logs myappYou can also inspect the PM2 startup service on a typical Ubuntu system:
systemctl status pm2-$(whoami)The service name can vary depending on the user and how PM2 was configured.
If the service is missing or inactive, revisit the startup instructions and check the service manager logs.
Step 7: Test an Actual Reboot
Do not assume that the configuration works just because PM2 reports that the application is running.
Test the behavior.
First, save the process list:
pm2 saveThen reboot the server during an appropriate maintenance window:
sudo rebootWait for the server to return, reconnect through SSH, and check:
pm2 statusIf the application appears in the process list and is running, test the actual website or API:
curl -I https://example.comA successful HTTP response is a useful sign, although you should also test application-specific endpoints.
If the application fails to return, inspect the PM2 logs and startup service logs rather than immediately restarting everything manually.
PM2 is useful because it handles both process management and startup restoration, but the startup configuration and saved process list must be set up correctly.
4. Method Two: Use systemd to Start the Application Automatically
Linux systems commonly use systemd to manage services.
You may already use systemd to manage Nginx, MongoDB, Redis, or other system services.
Instead of installing a separate process manager, you can create a systemd service for your Node.js application.
This approach is useful when you want your application to behave like a standard Linux service.
Step 1: Create a Dedicated Application User
Running your application as root is generally unnecessary and increases the impact of a security problem.
Create a dedicated user for the application:
sudo useradd --system --create-home --shell /usr/sbin/nologin myappThis creates a system account with a home directory and a shell that does not allow normal interactive login.
Make sure the application files are readable by this user.
For example, if the application is located at /var/www/myapp, you might assign ownership appropriately:
sudo chown -R myapp:myapp /var/www/myappOnly do this if the application user should own the entire directory. Some deployments use a separate deployment user and grant the runtime user read-only access to application files, with write access only to specific directories.
Choose permissions based on your deployment model.
Step 2: Create a systemd Service File
Create a service file:
sudo nano /etc/systemd/system/myapp.serviceAdd a configuration similar to the following:
[Unit]
Description=My Node.js Application
After=network.target
[Service]
Type=simple
User=myapp
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/node /var/www/myapp/server.js
Restart=on-failure
RestartSec=5
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.targetLet's understand the important settings.
Description
Provides a readable name for the service.
After=network.target
Specifies a startup ordering relationship with the network target. It does not necessarily mean that every remote service or database is ready to accept connections.
User=myapp
Runs the process under the dedicated application user.
WorkingDirectory
Sets the directory from which the application runs.
ExecStart
Specifies the executable and arguments used to start the application.
Restart=on-failure
Tells systemd to restart the service when it exits unsuccessfully, subject to systemd's restart limits and other settings.
RestartSec=5
Waits five seconds before attempting a restart.
Environment=NODE_ENV=production
Sets the production environment variable for the service.
The example assumes Node.js is installed at /usr/bin/node. Check its actual location before using this configuration:
which nodeIf Node.js is installed through NVM or another version manager, its location may differ. A system service does not automatically load your interactive shell configuration, so using the correct executable path is important.
Step 3: Configure Environment Variables
Many applications need credentials and connection strings, such as:
MONGODB_URIREDIS_URLJWT_SECRETPORT
Avoid hardcoding sensitive credentials directly into your service file.
Instead, create a protected environment file, for example:
sudo nano /etc/myapp.envAn example might look like this:
MONGODB_URI=mongodb://127.0.0.1:27017/myapp
PORT=3000
NODE_ENV=productionUse the actual connection details for your environment. Do not copy example credentials into production.
Restrict access to the file:
sudo chown root:myapp /etc/myapp.env
sudo chmod 640 /etc/myapp.envThen add this line to the [Service] section:
EnvironmentFile=/etc/myapp.envBe careful when editing environment files. They are not identical to every shell's .env syntax, and quoting or special characters may require attention.
For highly sensitive credentials, consider a dedicated secret-management solution rather than relying only on a local environment file.
Step 4: Enable and Start the Service
After creating the service file, tell systemd to reload its configuration:
sudo systemctl daemon-reloadEnable the service so it starts during system boot:
sudo systemctl enable myappStart it immediately:
sudo systemctl start myappCheck its status:
sudo systemctl status myappIf the service is active, you should see its current status and process information.
Step 5: Inspect Logs
If the service does not start, inspect its logs:
sudo journalctl -u myapp -n 100 --no-pagerTo follow new log entries in real time:
sudo journalctl -u myapp -fCommon errors include:
Incorrect Node.js executable paths.
Missing environment variables.
Incorrect file permissions.
Invalid database connection strings.
Application port conflicts.
Missing compiled files.
Database services that are not ready.
The logs usually provide more useful information than repeatedly restarting the service without investigating the underlying issue.
Step 6: Test the Restart Behavior
You can test systemd's process recovery by stopping the running application process unexpectedly in a controlled environment.
For a production service, do not test by killing processes during a critical period without a maintenance plan.
After confirming that restart behavior works, test a complete server reboot:
sudo rebootReconnect after the server returns and run:
sudo systemctl status myappIf the service is enabled and configured correctly, systemd should start it during boot.
The key difference is that systemctl enable configures startup behavior, while systemctl start starts the service immediately. In most deployments, you need both.
5. Method Three: Configure Docker to Restart Containers Automatically
If your application runs inside Docker, you can use Docker restart policies to control what happens when containers exit or the Docker daemon restarts.
For example, you might have a Node.js API running inside a container behind Nginx.
A restart policy can help recover the application after a server reboot without requiring you to start the container manually.
Step 1: Understand Docker Restart Policies
Docker supports several restart policies.
Policy | Behavior |
|---|---|
| Does not automatically restart the container |
| Restarts the container when it exits with an error, subject to the configured retry limit |
| Restarts the container when it exits and generally restarts it when the Docker daemon starts |
| Restarts the container unless it was explicitly stopped, including across daemon restarts |
For many long-running production services, unless-stopped is a reasonable starting point.
However, the correct choice depends on your deployment and operational requirements.
Step 2: Configure a Restart Policy
If you create a container manually, you can specify the policy when running it:
docker run -d \
--name myapp \
--restart unless-stopped \
-p 127.0.0.1:3000:3000 \
myapp:latestThis example publishes the container's port 3000 on the host's loopback interface.
That means the application can be accessed locally by a reverse proxy running on the same host, but it is not directly published on every host network interface.
This configuration assumes the application listens on the appropriate interface inside the container. A containerized application commonly needs to listen on 0.0.0.0 within the container for Docker's port forwarding to work.
If Nginx runs in a separate container, the networking setup will be different. You would normally connect the containers through a Docker network instead.
Step 3: Use Docker Compose
For applications managed through Docker Compose, configure the restart policy in the Compose file:
services:
app:
build: .
container_name: myapp
restart: unless-stopped
ports:
- "127.0.0.1:3000:3000"
environment:
NODE_ENV: productionStart the application:
docker compose up -dCheck its status:
docker compose psInspect its logs:
docker compose logs -f appDocker Compose can also manage databases, caches, and other application components, but each service should be configured according to its own requirements.
For example, restarting an API container does not guarantee that MongoDB is ready to accept connections.
Your application should handle temporary database failures and retry connections appropriately.
Step 4: Verify Docker Starts During Boot
The Docker daemon itself must be enabled to start during system startup.
On a typical systemd-based Linux server, check:
sudo systemctl status dockerIf Docker is installed as a systemd service and you want it to start automatically, use:
sudo systemctl enable dockerThe exact service name and installation method may differ.
Also remember that Docker restart policies are not a complete application health-management system. A container can remain running even when the application inside it is unable to serve requests.
Use application health checks, logs, and external monitoring to detect these situations.
6. Automatic Restart Does Not Mean the Application Is Healthy
This is one of the most important things to understand.
Suppose your application starts, tries to connect to MongoDB, and exits because the database is unavailable.
A process manager may restart it after a few seconds. If MongoDB is still unavailable, the application may fail again.
The process can continue restarting without ever becoming healthy.
Similarly, a Node.js process might remain alive while its API endpoints return errors.
Automatic restarts solve some process-lifecycle problems, but they do not fix every application failure.
Handle database connection failures
Your application should handle connection errors appropriately.
For example, if you use Mongoose, connect to MongoDB during application initialization and avoid marking the application ready until the required services are available.
A simplified example:
import mongoose from "mongoose";
import app from "./app.js";
const PORT = process.env.PORT || 3000;
async function startServer() {
try {
await mongoose.connect(process.env.MONGODB_URI);
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
} catch (error) {
console.error("Application startup failed:", error.message);
process.exit(1);
}
}
startServer();This example exits if the initial database connection fails, allowing a process manager configured to restart failed processes to try again.
For a real production application, you should also consider graceful shutdown, connection retry strategies, readiness checks, and how the application behaves if the database becomes unavailable after startup.
Avoid creating an aggressive restart loop that repeatedly overwhelms an already struggling dependency.
Add a health-check endpoint
A basic health endpoint can help monitoring tools determine whether the application is responding:
app.get("/health", (req, res) => {
res.status(200).json({
status: "ok",
timestamp: new Date().toISOString(),
});
});This only checks whether the endpoint responds. It does not verify database or cache availability.
For a more useful production setup, distinguish between a simple liveness check and a readiness check that verifies whether the application can safely serve requests.
Do not expose sensitive infrastructure details through public health endpoints.
7. Check Nginx After the Application Restarts
Many production applications use Nginx as a reverse proxy.
For example, Nginx might receive requests on HTTPS and forward them to a Node.js application running on port 3000.
A simplified configuration could look like this:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}This example illustrates reverse proxying over HTTP. A real production website should use an appropriately configured HTTPS server block and certificate.
If Nginx starts before your Node.js application is ready, visitors may temporarily receive a 502 Bad Gateway response.
Check Nginx's status:
sudo systemctl status nginxValidate its configuration:
sudo nginx -tInspect recent logs:
sudo journalctl -u nginx -n 100 --no-pagerYou can also test the backend directly from the server:
curl -I http://127.0.0.1:3000If the backend responds but the public website does not, investigate Nginx, TLS, DNS, and firewall configuration.
If the backend does not respond, focus on the application service and its dependencies first.
8. Common Mistakes That Prevent Automatic Startup
Even when developers configure a process manager, small mistakes can prevent an application from starting after a reboot.
Mistake 1: Forgetting to save the PM2 process list
Running:
pm2 startupdoes not replace the need to save the application list.
After adding the required applications, run:
pm2 saveIf the saved list is outdated, PM2 may not restore the applications you expect.
Mistake 2: Running PM2 under the wrong user
PM2 maintains separate state for different users.
If you start the application as one user but configure startup for another, the startup service may restore a different process list.
Use a consistent user account and follow PM2's generated startup instructions.
Mistake 3: Using the wrong Node.js path
An application may run successfully in your SSH terminal because your shell loads NVM or another version manager.
However, a systemd service may not load the same shell configuration.
Check the actual Node.js executable path and use the correct one in your service definition.
Mistake 4: Missing environment variables
Your application might depend on variables defined in an interactive shell or a local .env file.
A startup service will not necessarily load those variables automatically.
Configure them explicitly through a protected environment file, your process manager, or a secret-management system.
Mistake 5: Assuming dependencies are ready
Your application might start before its database, Redis instance, or external dependency is ready.
Use suitable startup ordering where appropriate, but also build retry behavior into the application.
Mistake 6: Testing only with manual restarts
An application that starts correctly when you run npm start manually may still fail under systemd, PM2, or Docker.
Test the actual production startup configuration, including a full server reboot.
9. How to Verify Automatic Restart After a Server Reboot
Once the configuration is complete, use a structured verification process.
Step 1: Confirm the application is running.
For PM2:
pm2 statusFor systemd:
sudo systemctl status myappFor Docker:
docker psStep 2: Confirm automatic startup is enabled.
For systemd:
sudo systemctl is-enabled myappFor Docker:
sudo systemctl is-enabled dockerThe Docker check applies to systems where Docker is managed through a systemd service.
For PM2, check its startup service and confirm that the process list has been saved.
Step 3: Reboot during a suitable maintenance window.
sudo rebootStep 4: Reconnect after the server returns.
Check the service or container status again.
Step 5: Test the application.
For a local backend:
curl -I http://127.0.0.1:3000For the public website:
curl -I https://example.comUse the correct endpoint for your application. Some APIs do not return a successful response to a HEAD request, so test a known health endpoint if necessary.
Step 6: Inspect logs if something fails.
For systemd:
sudo journalctl -u myapp -b --no-pagerFor PM2:
pm2 logs myappFor Docker Compose:
docker compose logs --tail=100 appThis final step is important because an application can be configured for automatic startup and still fail because of a missing file, invalid configuration, unavailable database, or incorrect permissions.
10. Which Approach Should You Choose?
For most developers running Node.js applications on a VPS, the decision comes down to how the application is deployed and maintained.
Choose PM2 when you want a convenient Node.js process manager with application logs, process monitoring, and straightforward startup configuration.
Choose systemd when you want to manage your application as a native Linux service and prefer built-in service management.
Choose Docker restart policies when your application already runs in containers and you want Docker to manage container restarts.
For larger containerized environments, orchestration platforms such as Kubernetes provide additional workload-management and recovery capabilities, but they also introduce operational complexity.
Avoid combining multiple process managers for the same application unless you have a specific reason and understand how they interact. For example, managing the same Node.js process independently through both PM2 and systemd can make troubleshooting confusing.
Select one primary process-management approach and configure it correctly.
Conclusion
Configuring automatic application restart after a server reboot is an important part of running a reliable production application.
If you start your application manually through SSH, it may stop when the server shuts down and fail to return when Linux boots again. A process manager or service manager solves this by restoring the application automatically.
For Node.js projects, PM2 provides a convenient way to manage processes and configure startup behavior. With systemd, you can create a dedicated Linux service that starts at boot and restarts after certain failures. If you use Docker, restart policies can help containers return after a restart.
However, automatic restarts should be only one part of your production setup. Your application also needs correct environment variables, appropriate permissions, database connection handling, useful logs, and health monitoring.
Most importantly, test the complete setup by rebooting the server in a controlled maintenance window. Confirm that the application starts, dependencies become available, and users can access the website or API without manual intervention.
A production application should not depend on someone logging into a server and starting it manually. Configure startup properly, test recovery, and make sure your application can handle failures gracefully.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


