Skip to content

Instantly share code, notes, and snippets.

@gtitov
Created September 25, 2024 09:07
Show Gist options
  • Save gtitov/7ac880d59fe5693e621253d68e0facde to your computer and use it in GitHub Desktop.
Save gtitov/7ac880d59fe5693e621253d68e0facde to your computer and use it in GitHub Desktop.
How to create a systemd service

source https://www.shubhamdipt.com/blog/how-to-create-a-systemd-service-in-linux/

  1. cd /etc/systemd/system
  2. Create a file named your-service.service and include the following
[Unit]
Description=<description about this service>

[Service]
User=<user e.g. root>
WorkingDirectory=<directory_of_script e.g. /root>
ExecStart=<script which needs to be executed>
# optional items below
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
[Unit]
Description=<project description>

[Service]
User=<user e.g. root>
WorkingDirectory=<path to your project directory containing your python script>
ExecStart=/home/user/.virtualenv/bin/python main.py
# optional items below
Restart=always
RestartSec=3
# replace /home/user/.virtualenv/bin/python with your virtualenv and main.py with your script

[Install]
WantedBy=multi-user.target
[Unit]
Description=<project description>

[Service]
User=<user e.g. root>
WorkingDirectory=<path to your project directory>
ExecStart=/bin/bash -c 'cd /home/ubuntu/project/ && source venv/bin/activate && python test.py'
# optional items below
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
  1. Reload the service files to include the new service. sudo systemctl daemon-reload

  2. Start your service sudo systemctl start your-service.service

  3. To check the status of your service sudo systemctl status example.service

  4. To enable your service on every reboot sudo systemctl enable example.service

  5. To disable your service on every reboot sudo systemctl disable example.service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment