Write Your Own systemd Service Intermediate 35 min
Lab overview

Write Your Own systemd Service

35 min 4 checked steps Intermediate
The situation

The shop's Python API is started by hand in a terminal. When the terminal closes, the server reboots or the app crashes, the shop is down until somebody notices. You will turn it into a proper systemd service that starts at boot, runs as its own user, comes back by itself after a crash and gets its settings from the unit file.

By the end of this lab you will be able to
  • Explain why apps started by hand are not reliable
  • Write a unit file and explain every line in it
  • Use daemon-reload, enable --now and status to bring a new service up
  • Make a service restart itself after a crash, and prove it
  • Change a service's settings with Environment= and apply the change correctly

From "a script someone runs" to "a service"

In the systemd Basics lab you managed nginx, a service that came with its own unit file when you installed the package. Your own applications don't come with one. Until you write it, your app is just a program that somebody has to start by hand, and that is fragile:

ProblemWhat happens
The terminal closesthe app is killed with it
The server rebootsthe app doesn't come back
The app crashes at 3 a.m.it stays down until a human notices
It runs as your user or as roota bug in the app can damage the whole system
Its output goes to your screenthe logs are lost when you close the window

A unit file fixes all five. It's a short text file that tells systemd how to run your app: the command, the user, what to do when it dies, and when to start it.

The app in this lab

/opt/shop/app.py is a small web API written in Python. It reads two settings from environment variables (named values a program can read when it starts):

VariableDefaultMeaning
PORT8000the port it listens on
SHOP_ENVdevelopmentwhich environment it's running in

Your unit files go in /etc/systemd/system/. That folder is for files written by administrators, while /usr/lib/systemd/system/ holds the ones installed by packages. If both have a file with the same name, yours wins.

The steps
1
Run the app by handStart the API manually, save its answer, then stop it again.
2
Write the unit fileCreate shop.service and get it running and enabled at boot as the shop user.
3
Make it heal itselfCrash the API on purpose and confirm systemd restarts it.
4
Change its settingsMove the API to port 8080 in production mode by editing the unit file.
How this lab works
  1. Press Start lab. You get your own Ubuntu machine on the right, just for you.
  2. Read each step. Commands with a ▶ Run button can be sent to the terminal in one click, but typing them yourself helps you remember.
  3. Do the Your task part, then press Check my work. The check looks at the machine and tells you what is right or still missing.
  4. Stuck? Open the hint. Nothing you do here can break anything real.
Step 1 of 4

Run the app by hand

Objective

Start the API manually, save its answer, then stop it again.

Before writing a service, always run the program by hand once. If it doesn't work by hand, it won't work as a service either, and errors are much easier to read on your own screen. This is also where you note the exact command that starts it, because the unit file will need it.

1. Run it in the foreground

bash
python3 /opt/shop/app.py
PartMeaning
python3the Python interpreter, which runs Python programs
/opt/shop/app.pythe program to run, given with its full path

What it does: starts the API in the foreground: it takes over your terminal and keeps running until you stop it.

text
shop-api listening on port 8000 (env=development)

The app tells you its port and environment, then waits for requests. Your prompt doesn't come back, because the terminal now belongs to the app. Press Ctrl + C to stop it. That sends the "interrupt" signal, and the app exits.

That's the first problem in action: the app only lives as long as this terminal is busy with it.

2. Run it in the background

bash
python3 /opt/shop/app.py &

What the & does: runs the command in the background. The app keeps running, and you get your prompt back straight away.

text
[1] 412
shop-api listening on port 8000 (env=development)
  • [1] is the job number: this shell's own short name for the background program.
  • 412 is its process ID (yours will differ).
  • Then the app prints its start-up line. Press Enter if your prompt looks hidden behind it.

3. Talk to it

bash
curl -s localhost:8000
PartMeaning
curlmakes a web request from the command line
-ssilent: no progress bar
localhost:8000this machine, port 8000, where the app listens
text
request: "GET / HTTP/1.1" 200 -
{"service": "shop-api", "status": "ok", "env": "development", "pid": 412}
  • The first line is the app's own log, printed to your terminal because it was started from it. 200 is the HTTP code for "OK". Once the app runs as a service, this kind of line will go to the journal instead.
  • The second line is the answer: JSON (a common data format) saying the service is OK, in development mode, with its process ID.

4. Stop it

bash
kill %1

What it does: kill sends a signal asking a process to stop. %1 means "job number 1 of this shell", so you don't need to type the PID. jobs lists your background jobs if you forget the number.

The app has to be stopped before the next step: only one program can listen on port 8000, and the service you build next needs that port.

  1. Start the API in the background.
  2. Save its answer to /root/manual.json.
  3. Stop the API again, so port 8000 is free.

Expected result: /root/manual.json contains "status": "ok", and curl localhost:8000 now fails with "Connection refused".

Hint: the commands, explained
text
python3 /opt/shop/app.py &
curl -s localhost:8000 > /root/manual.json
kill %1

What each part does

  • python3 /opt/shop/app.py &: start the app by hand in the background, the "before systemd" way.
  • curl -s localhost:8000 > FILE: call it and save the reply, proving it works.
  • kill %1: stop job number 1 of this shell (the & job). If your terminal closes, it would die anyway: that's the problem a service fixes.
Step 2 of 4

Write the unit file

Objective

Create shop.service and get it running and enabled at boot as the shop user.

A unit file is an INI-style text file: sections in [square brackets], each followed by Key=value lines. A service needs three sections:

SectionAnswers the question
[Unit]What is this, and what does it depend on?
[Service]How exactly do I run it?
[Install]When should it start, if someone runs enable?

The file name becomes the service name: shop.service is controlled with systemctl ... shop.

1. Create the file

bash
nano /etc/systemd/system/shop.service

What it does: opens the text editor nano on a new, empty file. Type or paste the content below. Save with Ctrl + O then Enter, and exit with Ctrl + X.

text
[Unit]
Description=Shop API
After=network.target

[Service]
User=shop
ExecStart=/usr/bin/python3 /opt/shop/app.py
Restart=always
RestartSec=2

[Install]
WantedBy=multi-user.target

Every line explained:

LineWhat it means
Description=Shop APIthe human-friendly name shown in systemctl status and in logs
After=network.targetif both start at boot, start this after networking. It only sets the order, it doesn't start networking.
User=shoprun the app as the shop user (already created for you), not root. If the app is ever hacked, the attacker only gets the limited rights of shop.
ExecStart=/usr/bin/python3 /opt/shop/app.pythe exact command to start the app, the same one you ran by hand. Always use full paths: systemd doesn't use your shell's PATH. which python3 tells you the full path.
Restart=alwaysif the process ever exits, start it again. You'll test this in the next step.
RestartSec=2wait 2 seconds before restarting, so a broken app doesn't restart hundreds of times a second
WantedBy=multi-user.targetmulti-user.target means "the system has booted normally". enable will hook the service in there, so it starts at every boot.

2. Tell systemd the file exists

bash
systemctl daemon-reload

What it does: systemd reads unit files into memory when it starts. daemon-reload makes it read all unit files again, so it picks up new and changed ones. Run it every time you create or edit a unit file. It prints nothing and doesn't restart any service.

3. Start it now and at every boot

bash
systemctl enable --now shop
PartMeaning
enablestart at boot (creates a link in multi-user.target.wants/)
--nowand also start it right now
shopthe service name: the file name without .service
text
Created symlink /etc/systemd/system/multi-user.target.wants/shop.service → /etc/systemd/system/shop.service.

That's the link that makes it start at boot, exactly what you saw being removed when you disabled nginx in the basics lab.

4. Check it

bash
systemctl status shop --no-pager
text
● shop.service - Shop API
     Loaded: loaded (/etc/systemd/system/shop.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-11-24 14:50:06 IST; 1s ago
   Main PID: 150 (python3)
      Tasks: 1 (limit: 9605)
     Memory: 11.8M ()
     CGroup: /system.slice/shop.service
             └─150 /usr/bin/python3 /opt/shop/app.py

Nov 24 14:50:06 devopsshack systemd[1]: Started shop.service - Shop API.
Nov 24 14:50:06 devopsshack python3[150]: shop-api listening on port 8000 (env=development)
  • Loaded: your file in /etc/systemd/system/, and enabled.
  • Active: active (running): it's up.
  • Main PID 150: the app's process.
  • The last line is the app's own start-up message. It no longer goes to a terminal: systemd captured it into the journal.

Now confirm it really runs as shop, and that it answers:

bash
ps -o pid,user,cmd -p $(systemctl show -p MainPID --value shop)
curl -s localhost:8000

What $( ... ) does: runs the command inside first and puts its output in its place. So the shell first asks systemd for the main PID, then runs ps -p 150.

text
    PID USER     CMD
    150 shop     /usr/bin/python3 /opt/shop/app.py
text
{"service": "shop-api", "status": "ok", "env": "development", "pid": 150}

The USER column says shop, not root.

If status shows failed instead, the answer is almost always in the log lines at the bottom, or in journalctl -u shop. Typical causes: a typo in the path in ExecStart, a forgotten daemon-reload, or the port still being used by the copy you started by hand.

Create /etc/systemd/system/shop.service as shown, then make the service running and enabled.

Expected result: systemctl is-active shop prints active, systemctl is-enabled shop prints enabled, and the app runs as the shop user.

Hint: the commands, explained

After saving the file in nano:

text
systemctl daemon-reload
systemctl enable --now shop
systemctl status shop --no-pager

What each part does

  • systemctl daemon-reload: make systemd re-read unit files. Needed after creating or editing one.
  • enable --now shop: start at every boot and start now.
  • status shop --no-pager: shows active (running), the main PID and the latest log lines.
Step 3 of 4

Make it heal itself

Objective

Crash the API on purpose and confirm systemd restarts it.

Apps crash: a bug, a memory spike, an unexpected input. Because systemd started the app, it is the app's parent, and the kernel tells it the moment the app dies. With Restart=always in the unit file, systemd waits RestartSec seconds and starts it again. Often the service is back before monitoring even notices.

The best way to trust this is to test it: crash the app on purpose and watch what happens.

1. Find the main process

bash
systemctl show -p MainPID --value shop

What it does: prints only the main PID of the service, for example 150.

2. Simulate a crash

bash
kill -9 $(systemctl show -p MainPID --value shop)
PartMeaning
killsend a signal to a process
-9signal number 9, SIGKILL: the kernel ends the process immediately. The app gets no chance to clean up, which is exactly what a real crash looks like.
$(systemctl show ...)the main PID, filled in automatically

3. Watch systemd react

Run this immediately:

bash
systemctl status shop --no-pager
text
● shop.service - Shop API
     Loaded: loaded (/etc/systemd/system/shop.service; enabled; preset: enabled)
     Active: activating (auto-restart) (Result: signal) since Tue 2026-11-24 14:50:07 IST; 3ms ago
  • activating (auto-restart): systemd saw the crash and is waiting the 2 seconds from RestartSec before starting it again.
  • Result: signal: why it died. The process was killed by a signal. If the app had exited with an error code, you'd see Result: exit-code.

Wait 3 seconds and run it again:

bash
systemctl status shop --no-pager
text
● shop.service - Shop API
     Loaded: loaded (/etc/systemd/system/shop.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-11-24 14:50:09 IST; 906ms ago
   Main PID: 164 (python3)

Running again, with a new Main PID (164 instead of 150): it's a fresh process.

4. Count the restarts

bash
systemctl show -p NRestarts --value shop

What it does: NRestarts is how many times systemd has automatically restarted this service. On a real server, a number that keeps climbing means the app keeps crashing, and someone should find out why.

text
1

5. Read the story in the journal

bash
journalctl -u shop --no-pager -n 8
PartMeaning
journalctlread the logs collected by systemd
-u shoponly the logs of the unit shop
--no-pagerprint everything at once
-n 8only the last 8 lines
text
Nov 24 14:50:06 devopsshack systemd[1]: Started shop.service - Shop API.
Nov 24 14:50:06 devopsshack python3[150]: shop-api listening on port 8000 (env=development)
Nov 24 14:50:07 devopsshack python3[150]: request: "GET / HTTP/1.1" 200 -
Nov 24 14:50:07 devopsshack systemd[1]: shop.service: Main process exited, code=killed, status=9/KILL
Nov 24 14:50:07 devopsshack systemd[1]: shop.service: Failed with result 'signal'.
Nov 24 14:50:09 devopsshack systemd[1]: shop.service: Scheduled restart job, restart counter is at 1.
Nov 24 14:50:09 devopsshack systemd[1]: Started shop.service - Shop API.
Nov 24 14:50:09 devopsshack python3[164]: shop-api listening on port 8000 (env=development)

Each line is: date and time, host name, who wrote it (systemd[1] is systemd itself, python3[150] is the app with its PID), then the message. Read it as a story:

  1. The app started as PID 150 and served a request.
  2. It was killed with signal 9 (status=9/KILL).
  3. systemd marked it failed, then 2 seconds later scheduled restart number 1.
  4. A new copy started as PID 164.

During a real incident, this is exactly the kind of story you'll be reading.

Restart=always restarts the app whenever it stops, even after a clean exit. Restart=on-failure only restarts it after a crash or an error exit code, which suits jobs that are supposed to finish. If an app crashes too often in a short time (by default 5 times in 10 seconds), systemd gives up and marks it failed, so a broken app doesn't restart forever.

Crash the shop API with kill -9, and let systemd restart it.

Expected result: systemctl show -p NRestarts --value shop prints 1 or more, and curl localhost:8000 still answers.

Hint: the commands, explained
text
kill -9 $(systemctl show -p MainPID --value shop)
sleep 3
systemctl show -p NRestarts --value shop

What each part does

  • systemctl show -p MainPID --value shop: print just the PID of the service's main process.
  • kill -9 PID: kill it hard, simulating a crash. sleep 3 waits for systemd to react.
  • show -p NRestarts --value: how many times systemd restarted it. It's 1 or more because the unit has Restart=on-failure.
Step 4 of 4

Change its settings

Objective

Move the API to port 8080 in production mode by editing the unit file.

The same app usually runs in several places (a developer's laptop, a test server, production) with different settings. Instead of changing the code, we pass settings in through environment variables. In a unit file, that's the Environment= line.

Changing a unit file is always the same three moves:

  1. edit the file,
  2. systemctl daemon-reload, so systemd reads the new version,
  3. systemctl restart shop, so the running app starts again with the new settings.

Forget step 2 and systemd keeps using the old file. Forget step 3 and the app keeps running with the old settings.

1. Add the settings

bash
nano /etc/systemd/system/shop.service

Add this line in the [Service] section, for example right above ExecStart=:

text
Environment=PORT=8080 SHOP_ENV=production

What it does: sets two environment variables for the app: PORT=8080 and SHOP_ENV=production. Separate several variables with spaces, or use several Environment= lines.

The [Service] section now looks like this:

text
[Service]
User=shop
Environment=PORT=8080 SHOP_ENV=production
ExecStart=/usr/bin/python3 /opt/shop/app.py
Restart=always
RestartSec=2

2. Restart without daemon-reload, to see the warning

bash
systemctl restart shop
text
Warning: The unit file, source configuration file or drop-ins of shop.service changed on disk. Run 'systemctl daemon-reload' to reload units.

systemd noticed the file changed, but it is still using the old version it has in memory. The app restarted on port 8000 again. Whenever you see this warning, run daemon-reload.

3. Do it properly

bash
systemctl daemon-reload
systemctl restart shop

What it does: the first command loads the new unit file, the second stops the app and starts it again with the new environment. Both print nothing when they work.

4. Check the result

bash
systemctl show -p Environment --value shop
curl -s localhost:8080
text
PORT=8080 SHOP_ENV=production
text
{"service": "shop-api", "status": "ok", "env": "production", "pid": 193}
  • systemd now passes both variables to the app.
  • The app answers on port 8080 and says "env": "production". curl localhost:8000 fails now, because nothing listens there any more.

For many settings, or for secrets like passwords, use EnvironmentFile=/etc/shop/shop.env instead: the variables then live in a separate file (one NAME=value per line) that you can protect with chmod 600. Another clean way to change units, especially ones that came from a package, is systemctl edit shop: it creates a small "drop-in" file with only your changes and runs daemon-reload for you.

Configure the shop service so the API listens on port 8080 with SHOP_ENV=production, and apply the change.

Expected result: curl -s localhost:8080 answers with "env": "production", and the service is still enabled and running.

Hint: the commands, explained
text
sed -i 's#^ExecStart=#Environment=PORT=8080 SHOP_ENV=production\nExecStart=#' /etc/systemd/system/shop.service
systemctl daemon-reload
systemctl restart shop

sed -i edits the file in place. Here it adds the Environment= line just above ExecStart=.

What each part does

  • sed -i 's#^ExecStart=#Environment=...\nExecStart=#': insert an Environment= line just above ExecStart=. The \n starts a new line.
  • Environment=PORT=8080 SHOP_ENV=production: variables the app sees when systemd starts it.
  • daemon-reload (the file changed), then restart so the running process picks up the new environment.
Lab complete

Brilliant work!

You turned a hand-started script into a production-style service: it starts at boot, runs as its own user, heals itself after a crash and takes its settings from the unit file.

Interview-ready takeaways:

  • Your own unit files go in /etc/systemd/system/NAME.service, with [Unit], [Service] and [Install] sections.
  • The key lines: ExecStart= (full paths), User= (never root unless you must), Restart=always or on-failure with RestartSec=, and WantedBy=multi-user.target so enable works.
  • After every edit: systemctl daemon-reload, then restart. The "changed on disk" warning means you forgot the reload.
  • Test self-healing with kill -9, then check NRestarts and read the crash story with journalctl -u NAME.
  • Settings come in through Environment= or EnvironmentFile=. systemctl edit creates a drop-in override.

Next: the Logs with journalctl lab.

root@devopsshack offline

Your Linux machine is ready to launch

Starting gives you a private Ubuntu server for up to 45 minutes. It is deleted when you finish.

Feedback