Home

How to start your project using systemd service

In this guide I'll show you how you can utilize systemd service to start long-running command on server boot.

cover image

About

Before we start let me explain why should use this to start your project.

Systemd is a process manager that can start, stop, and manage processes on your machine. You can order it when to start, what command to execute, restart it on crash and more.

This is really helpful because, if correctly done, service will ensure maximum uptime of the project, even if it crashes for some reason.

Guide

Creating a service is really easy.

First, we need to create a file called myapp.service in /etc/systemd/system/ directory. You can name it however you want, it just needs to have .service as an extension.

touch /etc/systemd/system/myapp.service # creating a desired file

Next, open up that file with the editor of your choice.

nano /etc/systemd/system/myapp.service # opening file using Nano

and past code below in it.

[Unit] After=network.service Description="My app" # Don't forget to change paths and commands # to ones that suit your project [Service] # current working directory (where your app lives) WorkingDirectory=/home/myapp # setting ENV variables Environment=NODE_ENV="production" Environment=PORT=3000 # start your app with the command ExecStart=yarn start # always restart the app if it crashes Restart=always # if the crash happens, wait 3 seconds before restarting RestartSec=3 # Run this service automatically after boot: [Install] WantedBy=multi-user.target

After creating and saving this configuration, you need to give it the correct permissions

chmod 777 /etc/systemd/system/myapp.service

The next step is to start our service. YAY!

First, we need to create a symlink, and we do that by enabling the service

systemctl enable myapp

After that, we have to start our newly created service

systemctl start myapp

After starting the successfully service no message should be printed in the console. To see if our service is working we will use

systemctl status myapp

If you see similar output to this

* myapp.service - myapp Loaded: loaded (/etc/systemd/system/myapp.service; disabled; vendor preset: enabled) Active: active (running) since Sun 2020-11-01 21:34:24 UTC; 5s ago Main PID: 25012 (node) Tasks: 7 (limit: 38054) Memory: 50.8M CGroup: /system.slice/myapp.service `-25012 /usr/bin/node /home/myapp Nov 01 21:34:24 45783 systemd[1]: Started myapp. Nov 01 21:34:25 45783 node[25012]: > Read on http://localhost:3000

then your service is working as it should, and you will be able to visit your app by visiting the server's IP.

Commands

Enable, Disable service

systemctl enable myapp systemctl disable myapp

Start, Restart, Stop service

systemctl start myapp systemctl restart myapp systemctl stop myapp

Check service's status

systemctl check myapp