Using linger with Node.js

 

Overview

This article explains how to use linger with a Node.js application. This combination allows your app to run persistent processes and your services to restart if your app crashes or the server reboots.

Prerequisites

This article assumes you have completed the following steps:

Step 1 — Installing linger

To install linger under your user, log in to your server via SSH and run the following command:

[server]$ loginctl enable-linger

This command will not respond with any output.

Step 2 — Configuring systemd user unit

This step configures Node to work with systemd user units on the server.

  1. Create the following directories:
    [server]$ mkdir -p ~/.config/systemd/user/
  2. Create a myapp.service file in the .config/systemd/user directory:
    [server]$ nano ~/.config/systemd/user/myapp.service
  3. Add the following code to this file:
    [Unit]
    Description=Systemd instance to serve Node application
    After=network.target
    
    [Service]
    WorkingDirectory=/path/to/your/app
    ExecStart=/usr/bin/node /path/to/your/app/app.js
    Environment="PATH=/usr/bin:/usr/local/bin"
    Environment=NODE_ENV=production
    ExecReload=/bin/kill -s HUP $MAINPID
    KillMode=mixed
    TimeoutStopSec=5
    PrivateTmp=true
    Restart=on-failure
    
    [Install]
    WantedBy=default.target
  4. Edit the highlighted lines above as follows:
    • WorkingDirectory: The path to your website application.
    • ExecStart: The path to your node installation.
  5. Enable the user unit for your Node app:
    [server]$ systemctl --user enable myapp
  6. Start the user unit for your Node app:
    [server]$ systemctl --user start myapp
  7. Confirm it is running:
    [server]$ systemctl --user status myapp

Your app's services will now automatically restart when the server reboots or if the application crashes.

See also

Did this article answer your questions?

Article last updated PST.

Still not finding what you're looking for?