Write Your Own systemd Service
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.
- 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:
| Problem | What happens |
|---|---|
| The terminal closes | the app is killed with it |
| The server reboots | the 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 root | a bug in the app can damage the whole system |
| Its output goes to your screen | the 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):
| Variable | Default | Meaning |
|---|---|---|
PORT | 8000 | the port it listens on |
SHOP_ENV | development | which 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.
- Press Start lab. You get your own Ubuntu machine on the right, just for you.
- Read each step. Commands with a ▶ Run button can be sent to the terminal in one click, but typing them yourself helps you remember.
- 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.
- Stuck? Open the hint. Nothing you do here can break anything real.
Run the app by hand
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
python3 /opt/shop/app.py| Part | Meaning |
|---|---|
python3 | the Python interpreter, which runs Python programs |
/opt/shop/app.py | the 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.
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
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.
[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.412is its process ID (yours will differ).- Then the app prints its start-up line. Press
Enterif your prompt looks hidden behind it.
3. Talk to it
curl -s localhost:8000| Part | Meaning |
|---|---|
curl | makes a web request from the command line |
-s | silent: no progress bar |
localhost:8000 | this machine, port 8000, where the app listens |
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.
200is 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
kill %1What 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.
- Start the API in the background.
- Save its answer to
/root/manual.json. - 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
python3 /opt/shop/app.py &
curl -s localhost:8000 > /root/manual.json
kill %1What 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.
Write the unit file
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:
| Section | Answers 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
nano /etc/systemd/system/shop.serviceWhat 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.
[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.targetEvery line explained:
| Line | What it means |
|---|---|
Description=Shop API | the human-friendly name shown in systemctl status and in logs |
After=network.target | if both start at boot, start this after networking. It only sets the order, it doesn't start networking. |
User=shop | run 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.py | the 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=always | if the process ever exits, start it again. You'll test this in the next step. |
RestartSec=2 | wait 2 seconds before restarting, so a broken app doesn't restart hundreds of times a second |
WantedBy=multi-user.target | multi-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
systemctl daemon-reloadWhat 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
systemctl enable --now shop| Part | Meaning |
|---|---|
enable | start at boot (creates a link in multi-user.target.wants/) |
--now | and also start it right now |
shop | the service name: the file name without .service |
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
systemctl status shop --no-pager● 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/, andenabled. - 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:
ps -o pid,user,cmd -p $(systemctl show -p MainPID --value shop)
curl -s localhost:8000What $( ... ) 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.
PID USER CMD
150 shop /usr/bin/python3 /opt/shop/app.py{"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:
systemctl daemon-reload
systemctl enable --now shop
systemctl status shop --no-pagerWhat 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: showsactive (running), the main PID and the latest log lines.
Make it heal itself
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
systemctl show -p MainPID --value shopWhat it does: prints only the main PID of the service, for example 150.
2. Simulate a crash
kill -9 $(systemctl show -p MainPID --value shop)| Part | Meaning |
|---|---|
kill | send a signal to a process |
-9 | signal 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:
systemctl status shop --no-pager● 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 agoactivating (auto-restart): systemd saw the crash and is waiting the 2 seconds fromRestartSecbefore 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 seeResult: exit-code.
Wait 3 seconds and run it again:
systemctl status shop --no-pager● 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
systemctl show -p NRestarts --value shopWhat 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.
15. Read the story in the journal
journalctl -u shop --no-pager -n 8| Part | Meaning |
|---|---|
journalctl | read the logs collected by systemd |
-u shop | only the logs of the unit shop |
--no-pager | print everything at once |
-n 8 | only the last 8 lines |
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:
- The app started as PID 150 and served a request.
- It was killed with signal 9 (
status=9/KILL). - systemd marked it failed, then 2 seconds later scheduled restart number 1.
- 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
kill -9 $(systemctl show -p MainPID --value shop)
sleep 3
systemctl show -p NRestarts --value shopWhat 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 3waits for systemd to react.show -p NRestarts --value: how many times systemd restarted it. It's 1 or more because the unit hasRestart=on-failure.
Change its settings
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:
- edit the file,
systemctl daemon-reload, so systemd reads the new version,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
nano /etc/systemd/system/shop.serviceAdd this line in the [Service] section, for example right above ExecStart=:
Environment=PORT=8080 SHOP_ENV=productionWhat 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:
[Service]
User=shop
Environment=PORT=8080 SHOP_ENV=production
ExecStart=/usr/bin/python3 /opt/shop/app.py
Restart=always
RestartSec=22. Restart without daemon-reload, to see the warning
systemctl restart shopWarning: 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
systemctl daemon-reload
systemctl restart shopWhat 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
systemctl show -p Environment --value shop
curl -s localhost:8080PORT=8080 SHOP_ENV=production{"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:8000fails 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
sed -i 's#^ExecStart=#Environment=PORT=8080 SHOP_ENV=production\nExecStart=#' /etc/systemd/system/shop.service
systemctl daemon-reload
systemctl restart shopsed -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 anEnvironment=line just aboveExecStart=. The\nstarts a new line.Environment=PORT=8080 SHOP_ENV=production: variables the app sees when systemd starts it.daemon-reload(the file changed), thenrestartso the running process picks up the new environment.
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=alwaysoron-failurewithRestartSec=, andWantedBy=multi-user.targetsoenableworks. - After every edit:
systemctl daemon-reload, thenrestart. The "changed on disk" warning means you forgot the reload. - Test self-healing with
kill -9, then checkNRestartsand read the crash story withjournalctl -u NAME. - Settings come in through
Environment=orEnvironmentFile=.systemctl editcreates a drop-in override.
Next: the Logs with journalctl lab.
Turn a script that someone runs by hand into a real service. Write a unit file line by line, start it at boot, run it as a safe user, make it restart itself after a crash and change its settings the right way.
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.