natbox.io

Guides / Keep an app running

Keep an app running with systemd

About 5 minutes. Debian, Ubuntu and AlmaLinux use systemd; Alpine notes at the end.

Make your app listen on one of your forwarded ports, for example 10002, on all addresses (0.0.0.0 and ::). Then it is reachable at natbox.io:10002 over IPv4 and on any of your IPv6 addresses.

1. Create a service

Save as /etc/systemd/system/myapp.service and adjust ExecStart:

[Unit]
Description=My app
After=network-online.target
Wants=network-online.target

[Service]
User=app
WorkingDirectory=/opt/myapp
Environment=PORT=10002
ExecStart=/usr/bin/node server.js
# or: ExecStart=/opt/myapp/venv/bin/python app.py
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
useradd -r -m -d /opt/myapp app
systemctl daemon-reload && systemctl enable --now myapp

2. Check on it

systemctl status myapp
journalctl -u myapp -f       # live logs
ss -tlnp | grep 10002        # is it listening?

Serving a website instead?

Put nginx in front on ports 80 and 443 and proxy to your app on localhost. See Host a website.

On Alpine

Alpine uses OpenRC. Create /etc/init.d/myapp with command="/usr/bin/node", command_args="/opt/myapp/server.js", command_background=true and pidfile="/run/myapp.pid", then rc-update add myapp && rc-service myapp start.