Run any app as a systemd service
systemd is the service manager that already runs inside your container. A systemd service keeps your program running after you close SSH, starts it on boot and restarts it after a crash. It works for any language and needs no extra installation. At the end of this guide, a small Python web server runs as a service on port 3000.
What you need
- An open SSH connection to your container. If you have not connected yet, follow Connect to your VPS over SSH.
- Python 3 to run the example. Check with
python3 -V; if the command is not found, install it withsudo apt install -y python3. You can replace the example with any other program.
1. Create an app to run
This guide uses a tiny Python web server as the example. To run your own app instead, adjust ExecStart in step 2. First create ~/hello/app.py, for example with nano:
mkdir -p ~/hello
nano ~/hello/app.pyfrom http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"Hello from systemd!\n")
HTTPServer(("0.0.0.0", 3000), Handler).serve_forever()2. Create the service file
systemd reads a service from a unit file, a small configuration file in /etc/systemd/system. The command below writes it for you, and your shell fills in $USER and $HOME.
sudo tee /etc/systemd/system/hello.service <<EOF
[Unit]
Description=Hello app
After=network.target
[Service]
User=$USER
WorkingDirectory=$HOME/hello
ExecStart=/usr/bin/python3 $HOME/hello/app.py
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOFThe main settings in the unit file:
Userruns the app as your user instead of root.ExecStartis the command to run. Use full paths in it;which python3shows where a program is installed.Restart=alwaysstarts the app again after a crash, andRestartSecwaits a few seconds first.- To pass settings to the app, add lines such as
Environment=PORT=3000under[Service], or setEnvironmentFile=to a file. For a Node.js app,Environment=NODE_OPTIONS=--max-old-space-size=256limits its memory.
3. Start it and enable it on boot
sudo systemctl daemon-reload
sudo systemctl enable --now hello
systemctl status hello
# give the app a second to start
sleep 1
curl http://localhost:3000The status should say active (running), and curl should print Hello from systemd!. To publish the app, add a route for port 3000 in Domain Routing, as described in Publish an app on a free subdomain.
Everyday commands
systemctl status helloshows whether the service is running and the last log lines.sudo journalctl -u hello -fshows the live logs.sudo systemctl restart hellorestarts the service, for example after you deploy new code.sudo systemctl disable --now hellostops the service and keeps it from starting on boot.- After you edit the unit file, run
sudo systemctl daemon-reloadand then restart the service.