Hacker, Concerned Citizen and Avid Reader. Interested in politics, economy and history. Founder & CEO of Melluli Technologies. Bengaluru, India

Image

Run Node App as Linux Service

This post describes how to run a NodeJS web application as a linux service with a dedicated user to get the benefits of systemd services.

To start with

Let us call our app my-nodejs-app. The application is deployed at /usr/share/my-nodejs-app. Here we also assume the NodeJS app uses standard express app template that creates an executable entry point at bin/www in the app source. If not then some of the paths below might need to be changes as per your executable path.

Create a dedicated user for the service

It is always better to run as much as possible any process without root privileges. So let us create a dedicated user for our NodeJS app -

1
useradd -r -s /bin/false my-nodejs-app-user
  • This creates a user who cannot login from SSH
  • It also creates corresponding group
  • It does not create home directory and we don’t need this user to have one

Grant the designated user access to the app directory

This is self explanatory

1
chown -R my-nodejs-app-user:my-nodejs-app-user /usr/share/my-nodejs-app

Write a systemd config file

Create a systemd config file as below at /etc/systemd/system/my-nodejs-app.service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[Unit]
Description=my-nodejs-app

[Service]
Type=simple
ExecStart=/bin/node /usr/share/my-nodejs-app/bin/www
WorkingDirectory=/usr/share/my-nodejs-app
User=my-nodejs-app-user

# Environment variables: production|development
Environment=NODE_ENV=production

# Allow many incoming connections
LimitNOFILE=infinity

# Allow core dumps for debugging
LimitCORE=infinity

StandardInput=null
StandardOutput=journal+console
StandardError=journal+console
Restart=always

[Install]
WantedBy=multi-user.target

Start the service

1
systemctl start my-nodejs-app

Verify

  • Verify the process has started -
    1
    
    systemctl status my-nodejs-app.service
    

    If all is well you should see active (running) message like -

    1
    2
    3
    
    my-nodejs-app.service - my-nodejs-app
     Loaded: loaded (/etc/systemd/system/my-nodejs-app.service; enabled; vendor preset: disabled)
     Active: active (running) since Sun 2021-05-23 09:49:02 UTC; 1min 28s ago
    
  • Check additional information about the service -
    1
    
    journalctl -xe -u my-nodejs-app.service
    
  • Verify the process is running as the designated user and not root -
    1
    
    ps -aef --forest | grep my-nodejs-app
    

    The above command should show an output like this -

    1
    
    my-node+  1202     1  0 09:49 ?        00:00:01 /bin/node /usr/share/my-nodejs-app/bin/www
    

Adios…