Shipping it with a systemd unit
The last chapter puts the server on a real machine: a user of its own, a unit file, logs in journald and a restart when it falls over.
The server from chapter 5 passes its tests and runs on my laptop. This chapter puts it on the mini PC under my desk, where it has to survive a reboot without me. No container: a user, a directory and a systemd unit.
A user of its own
The server never runs as root. It gets a system user without a shell and a directory it owns.
$ sudo useradd --system --home /srv/tiny-server --shell /usr/sbin/nologin tiny
$ sudo mkdir -p /srv/tiny-server
$ sudo chown tiny: /srv/tiny-server
$ sudo -u tiny node --version
v24.11.1The unit file
Two lines matter more than the rest. Restart=on-failure brings it back after a crash, and ProtectSystem=strict keeps it from writing anywhere but its own directory.
[Unit]
Description=Tiny HTTP server
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=tiny
WorkingDirectory=/srv/tiny-server
ExecStart=/usr/bin/node src/server.ts
Environment=PORT=8080
Restart=on-failure
RestartSec=2
ProtectSystem=strict
ReadWritePaths=/srv/tiny-server
ProtectHome=true
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.targetStart it and read the log
$ sudo systemctl daemon-reload
$ sudo systemctl enable --now tiny-server
Created symlink /etc/systemd/system/multi-user.target.wants/tiny-server.service
$ journalctl -u tiny-server -n 3
Nov 16 08:12:04 desk-pc node[4121]: Listening on :8080
Nov 16 08:12:09 desk-pc node[4121]: GET /posts/hello 200 1.2 ms
Nov 16 08:12:11 desk-pc node[4121]: GET /nope 404 0.4 msconsole.log from chapter 4 ends up in journald with a timestamp and the process id. I removed the timestamps the logging middleware wrote itself; journald’s are enough.
What the series built
- A server on
node:httpthat answers withResponseobjects (chapters 1 and 2). - A router in 20 lines with parameters (chapter 3).
- Middleware as functions that wrap a handler (chapter 4).
- Tests with
node:test, no framework (chapter 5). - A unit file that restarts it and keeps it in its directory (this chapter).
That is everything stummel used in its first year. The code of every chapter is in the archive at the end of chapter 3, and in the repository on example.com.
subscribe
New entries and the next chapter by mail, nothing else.