At two in the morning PostgreSQL (the database notes-api uses) went down for a moment. notes-api crashed (stopped because of an error), and nothing started it again until you woke up. The next week the server was rebooted for an update, and once again the app didn't start with it. On Linux, the program that manages this is systemd.
systemd is the first program that runs when a Linux server boots. It starts, watches and records the output of every service: a program that must keep running, like notes-api. Each service has a unit file, a settings file that systemd reads. Picture the service as an employee, and the unit file as that employee's duty card. The card says who does the work (User=) and what they bring along (EnvironmentFile=). It also says what happens if they collapse, that is, if the app crashes (Restart=), and whether they come in every morning, that is, on every boot (enable). The basics of systemctl, daemon-reload and journalctl are in the systemd & Services lesson of the Terminal track. Here we write a production unit file for notes-api on web-1.
The notes-api unit file
This unit file has three sections (parts): [Unit], [Service] and [Install]. The first line, starting with #, only notes where the file is:
# /etc/systemd/system/notes-api.service
[Unit]
Description=notes-api
After=network.target postgresql.service
Requires=postgresql.service
[Service]
User=www-data
WorkingDirectory=/srv/notes-api
ExecStart=/usr/bin/node app.js
Environment=NODE_ENV=production
Environment=PORT=3000
EnvironmentFile=/etc/notes-api.env
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
User=www-data: the app runs aswww-data, the user allowed to write instorage/(the File System & Permissions lesson). Without this line, the app runs as root.WorkingDirectory=andExecStart=: the folder the app runs in, and the command that starts it.ExecStartshould use a full path (/usr/bin/node): systemd does not use yourPATH(the list of folders where the shell looks for programs), so a program you installed with nvm (a tool that installs Node) is not found.Environment=sets environment variables that are not secret.EnvironmentFile=readsKEY=VALUElines from a file. systemd reads it as root, then hands the values to the app. That is why the secret file may be600owned by root.Restart=on-failureandRestartSec=5: if the app crashes, start it again five seconds later.WantedBy=multi-user.targetin[Install]is used bysystemctl enable. It means the service is started when the system reaches the multi-user target, a server's normal state without a desktop.
After= and Requires=
| Line | Meaning | When PostgreSQL is stopped |
|---|---|---|
After=postgresql.service |
order only: notes-api starts after PostgreSQL | notes-api keeps running, its queries (commands to the database) fail |
Requires=postgresql.service |
a hard dependency: PostgreSQL is started too | notes-api is stopped with it |
After= only sets the start order. Requires= ties the service to its dependency (the service it needs, here PostgreSQL):
- When the dependency is stopped on purpose (for example
systemctl stop postgresql), your service stops too. When the dependency is restarted on purpose, your service is restarted too. - When the dependency fails to start, your service is not started. This rule holds because the notes-api unit also has
After=. - When the dependency crashes on its own, your service keeps running. To stop on a crash too, use
BindsTo=.
After= and Requires= are usually written as a pair, as in the notes-api unit. A softer version of Requires= is Wants=: the dependency is started too, but when it stops, your service keeps running.
Restart=: on-failure or always
When a program stops, it reports an exit code: 0 for a clean exit, another number when it failed. This table shows when systemd starts it again:
Restart= |
Exit 0 (clean exit) | Exit other than 0 (crash) | systemctl stop |
|---|---|---|---|
no (default) |
stays down | stays down | stays down |
on-failure |
stays down | restart | stays down |
always |
restart | restart | stays down |
For an HTTP server like notes-api, on-failure fits best: an app that crashes is started again, an app that exits cleanly is left alone. always suits a worker (a program that runs tasks in the background) that exits with 0 on purpose and must run again. systemctl stop never triggers a restart. This is the journal (the log systemd keeps) when PostgreSQL went down for a moment and the app crashed:
Oct 09 09:01:12 web-1 node[5120]: Database connection failed: connect ECONNREFUSED 127.0.0.1:5432
Oct 09 09:01:12 web-1 systemd[1]: notes-api.service: Main process exited, code=exited, status=1/FAILURE
Oct 09 09:01:12 web-1 systemd[1]: notes-api.service: Failed with result 'exit-code'.
Oct 09 09:01:17 web-1 systemd[1]: notes-api.service: Scheduled restart job, restart counter is at 1.
Oct 09 09:01:17 web-1 systemd[1]: Started notes-api.service - notes-api.
Oct 09 09:01:17 web-1 node[5207]: Server running at http://localhost:3000
The app crashed at 09:01:12, and systemd started it again at 09:01:17, five seconds later (RestartSec=5). The last line shows the app running again. But a restart does not fix a config. If the app fails because its secrets are empty, it fails again every five seconds, and the restart counter keeps climbing.
enable and start: two different things
start starts the service now. enable makes a symlink (a shortcut file that points to the unit file) in the folder multi-user.target.wants, so the service starts on every boot. enable does not start it now. In this example, ; runs two commands one after the other, and echo $? prints the exit code of the command before it:
deploy@web-1:~$ sudo systemctl enable notes-api
Created symlink /etc/systemd/system/multi-user.target.wants/notes-api.service → /etc/systemd/system/notes-api.service.
deploy@web-1:~$ systemctl is-active notes-api; echo $?
inactive
3
deploy@web-1:~$ sudo systemctl start notes-api
deploy@web-1:~$ systemctl is-active notes-api; echo $?
active
0
- After
enablealone,is-activeprintsinactive.sudo systemctl enable --now notes-apidoes both.disableundoesenable. systemctl is-activeprints the service's state and exits with exit code 0 when active, 3 when not. A deploy script can use it directly:if systemctl is-active --quiet notes-api; then ...runs the part afterthenonly when the exit code is 0.--quietmakes it print nothing.
Reading status and the journal
systemctl status shows the service's state with its latest log lines:
deploy@web-1:~$ systemctl status notes-api
● notes-api.service - notes-api
Loaded: loaded (/etc/systemd/system/notes-api.service; enabled; preset: enabled)
Active: active (running) since Fri 2026-10-09 09:00:09 BST; 3s ago
Main PID: 5120 (node)
Tasks: 7 (limit: 2274)
Memory: 41.6M (peak: 42.0M)
CPU: 389ms
CGroup: /system.slice/notes-api.service
└─5120 /usr/bin/node app.js
Oct 09 09:00:09 web-1 systemd[1]: Started notes-api.service - notes-api.
Oct 09 09:00:09 web-1 node[5120]: Server running at http://localhost:3000
Loaded:shows the unit file andenabledordisabled.Active:shows the state now:active (running),inactive (dead),failed, oractivating (auto-restart)while it waits to restart.- The two lines at the bottom come from the journal, where systemd keeps everything a service prints. When the app fails to start,
journalctl -u notes-api(-u: only this service's log) shows why. This is what you get when theEnvironmentFile=line was left out:
deploy@web-1:~$ journalctl -u notes-api -n 4
Oct 09 09:00:03 web-1 systemd[1]: Started notes-api.service - notes-api.
Oct 09 09:00:03 web-1 node[5120]: Config error: DATABASE_URL, JWT_SECRET not set. Copy .env.example to .env, then fill it in.
Oct 09 09:00:03 web-1 systemd[1]: notes-api.service: Main process exited, code=exited, status=1/FAILURE
Oct 09 09:00:03 web-1 systemd[1]: notes-api.service: Failed with result 'exit-code'.
The Config error line gives the reason: without EnvironmentFile=, the app does not get DATABASE_URL and JWT_SECRET. journalctl -u notes-api -f follows the log live, and -n 50 takes the last 50 lines.
A unit file put together from an object
In the exercise, generateUnitFile(config) builds the unit file's text from an object. Each section is lines joined with "\n", and sections are separated by one empty line ("\n\n"). The exercise's [Service] also has Type=simple. It is the default type for a service with ExecStart=, meaning the process that ExecStart runs is the service. When the after array is empty, the After= line is not written at all.
⚠️ Unit files that look right but aren't yet
- Only
enable, or onlystart. With onlystart, the service does not start again after a reboot. With onlyenable, it is not running yet. For a new service:enable --now. - Forgetting
User=. The service runs as root, so a security hole in the app becomes root access to the whole server. - A wrong
EnvironmentFile=path. systemd refuses to start withFailed to load environment files: No such file or directory. If the file really is optional, writeEnvironmentFile=-/etc/notes-api.env(a minus sign before the path). - Counting on
Restart=for a broken config. The app crashes again everyRestartSec. Readjournalctl -u, fix the cause, thenrestart. - Forgetting
daemon-reloadafter editing a unit. Without this command, which makes systemd read the unit files again, systemd keeps using the old version (see the systemd & Services lesson).
TL;DR: systemd (the Linux program that starts and watches services, programs that must keep running) reads each service's unit file (its settings file). notes-api's production unit file has three sections. [Unit]: After= (start order only) and Requires= (stops too when its dependency, here PostgreSQL, is stopped, but not when the dependency crashes: that is the job of BindsTo=). [Service]: User=www-data, an ExecStart= with a full path, EnvironmentFile=/etc/notes-api.env (read by systemd as root), Restart=on-failure and RestartSec=5. on-failure starts a crashed app again, but leaves exit 0 (a clean exit) and stop alone; always also starts it again after exit 0. [Install]: WantedBy=multi-user.target, so it starts at boot. start = now, enable = every boot, enable --now = both. systemctl is-active exits with exit code 0 when the service runs (use --quiet in a script). status shows the state and the latest log, and journalctl -u notes-api shows why the app failed.
⚡ A service's duty card
Write:
[Service]
User=www-data
ExecStart=/usr/bin/node app.js
EnvironmentFile=/etc/notes-api.env
Restart=on-failure
RestartSec=5
Meaning: This is the [Service] part of a unit file: the duty card of a service (a program that must keep running), read by systemd, the Linux program that starts and watches services. The app runs as the user www-data, not root. systemd reads the secret file as root, then hands its values to the app. If the app crashes (stops because of an error), systemd starts it again five seconds later.
⚡ After= and Requires=
Write:
[Unit]
After=network.target postgresql.service
Requires=postgresql.service
Guess first: PostgreSQL (the database notes-api uses) is stopped. With After= alone, what happens to notes-api?
notes-api keeps running, but its queries (commands to the database) fail. After= only sets the start order. Only with Requires= is notes-api stopped with it.
Meaning: After= = start order only. Requires= = a hard dependency (notes-api needs PostgreSQL): when PostgreSQL is stopped, notes-api stops too. If PostgreSQL crashes on its own, only BindsTo= stops notes-api as well.
⚡ start and enable are different
Write:
sudo systemctl enable --now notes-api
Meaning: start starts the service now, enable makes it start on every boot (when the server turns on). enable --now does both.
⚡ Why did it fail? Ask the journal
Write:
journalctl -u notes-api -n 4
Meaning: systemd keeps everything a service prints in the journal. -u notes-api picks the service, -n 4 takes the last 4 lines, and -f follows it live. A restart does not fix a config: read the reason first, fix it, then restart.