Running Your App as a systemd Service

systemd keeps your app running, restarts it on crash, and starts it on boot.

Running node server.js in an SSH session dies the moment you disconnect. Instead, register your app with systemd, the Linux service manager. It starts the app on boot, restarts it if it crashes, and captures logs.

A service unit

You write a .service file describing how to start the app, which user to run as, and the restart policy. Then systemctl enable --now starts it and makes it survive reboots.

Handy commands

  • systemctl status myapp — is it running?
  • systemctl restart myapp — restart after a deploy.
  • journalctl -u myapp -f — tail live logs.

Example

Example · yaml
# /etc/systemd/system/myapp.service
[Unit]
Description=MyApp Node server
After=network.target

[Service]
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node server.js
Environment=NODE_ENV=production
Environment=PORT=3000
User=appuser
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

When to use it

  • A Node.js API is registered as a systemd service so it automatically restarts if it crashes at 3am without any human intervention.
  • A team configures systemd to start their app after the network is ready so it never fails on reboot due to missing connectivity.
  • An operations engineer uses journalctl to stream structured logs from the systemd service unit into CloudWatch for centralised monitoring.

More examples

Create a systemd service unit file

Defines a systemd unit that runs the Node.js app as ec2-user, restarts on failure, and loads env vars from a file.

Example · bash
# /etc/systemd/system/myapp.service
[Unit]
Description=My Node.js App
After=network.target

[Service]
Type=simple
User=ec2-user
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node server.js
Restart=always
RestartSec=5
EnvironmentFile=/opt/myapp/.env

[Install]
WantedBy=multi-user.target

Enable and start the service

Registers the new unit file with systemd, enables it to survive reboots, and starts it immediately.

Example · bash
# Reload systemd, enable on boot, then start
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
sudo systemctl status myapp

Tail service logs with journalctl

Streams the service's stdout and stderr via journalctl so you can monitor it in real time after a deploy.

Example · bash
# Follow live logs for the service
sudo journalctl -u myapp -f --since '5 min ago'

Discussion

  • Be the first to comment on this lesson.
Running Your App as a systemd Service — AWS Deployment | SoundsCode