Skip to content

Instantly share code, notes, and snippets.

@ryanlelek
Last active July 14, 2024 20:38
Show Gist options
  • Save ryanlelek/1164853a4b80473afff61adc34a6450c to your computer and use it in GitHub Desktop.
Save ryanlelek/1164853a4b80473afff61adc34a6450c to your computer and use it in GitHub Desktop.
systemd service start on boot

README

Goal

Have a command run at boot

Summary

In 2024, we use systemd for this in all major distributions. There are other distributions that do not like systemd and are still using older initialization ("init") systems like "Sys-V" or alternatives like "runit". If you are unsure, you're probably running systemd and should follow this guide. You would usually know if you're using an alternative.

Requirements

  • Debian-based OS (Debian, Ubuntu, Mint, Raspbian)
  • RedHat-based OS (RHEL, CentOS, Rocky, Alma, Suse)

Instructions

  1. Pick a service name, like "script" or "server". We will use NAME to be a placeholder but you should swap in your service name
  2. Create or edit a file at /etc/systemd/system/NAME.service (See contents below)
  3. Add more environment variables, edit the parameters as needed.
  4. You may execute a script file (make sure it's executable!) or a command like you would on the command line
  5. If you only want the script to run once, instead of automatically restarting, switch "simple" to "oneshot"
  6. Run sudo chmod 660 /etc/systemd/system/NAME.service
  7. Run sudo systemctl daemon-reload to re-scan the files (we need to do this because you just created/edited one)
  8. Run sudo systemctl start NAME
  9. Verify your service started correctly with systemctl status NAME
  10. View logs if needed with sudo journalctl -n 20 -u NAME (returns the latest 40 lines)
  11. If you need to, you can restart the service with sudo systemctl restart NAME
  12. Run systemctl enable NAME to start this service automatically on boot/startup
  13. Test it by rebooting your system now
[Unit]
Description=myservice
[Service]
Type=simple
User=user
Group=user
Environment=SOMEVAR=myvalue
WorkingDirectory=/home/user
ExecStart=/home/user/scripts/script.sh
Restart=always
RestartSec=3
StartLimitBurst=5
StartLimitInterval=0
StandardOutput=journal
StandardError=journal+console
SyslogIdentifier=myservice
TimeoutSec=60
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment