How to create a custom Linux service via systemd

What is systemd and systemctl?

systemd is a Linux initialization system and service manager. systemd provides a logging daemon and other tools and utilities to help with common system administration tasks.

Its primary component is a "system and service manager" — an init system used to bootstrap user space and manage user processes.

systemctl - is a controlling interface and inspection tool for the systemd. You use this tool to perform administrative tasks and interact with systemd.

Prerequisites:

For demo purposes use the following Vagrantfile to create an Ubuntu-based machine:

Vagrant.configure("2") do |config|

  # VM machine configuration
  config.vm.provider :virtualbox do |v|
    v.customize ["modifyvm", :id, "--memory", 2048]
    # v.customize ["modifyvm", :id, "--cpus", 2]
  end

  # Ubuntu worker node
  config.vm.define "ubuntu" do |ubuntu|
    ubuntu.vm.box = "ubuntu/bionic64"
    ubuntu.vm.hostname = "ubuntu"
  end

end

Basic Vagrant commands:

  1. To start the machine:

     vagrant up
    
  2. To reload (halt and up):

     vagrant reload
    
  3. To check VM deployment use:

     vagrant global-status --prune
    
  4. To ssh into the machine use:

     vagrant ssh ubuntu
    

Create custom Linux service:

  1. As a demo use the following script `custom_service.sh` Bash script file:

     DATE=`date '+%Y-%m-%d %H:%M:%S'`
     echo "Custom service started at ${DATE}" | systemd-cat -p info
    
     while :
     do
     echo "Looping...";
     sleep 30;
     done
    

    The script logs the time and runs every 30 seconds

  2. Move the script to /usr/bin/ and make it executable:

     sudo mv custom_service.sh /usr/bin/custom_service.sh
     sudo chmod +x /usr/bin/custom_service.sh
    
  3. Create a Unit file to define a systemd service:

     [Unit]
     Description=Custom systemd service.
    
     [Service]
     Type=simple
     ExecStart=/bin/bash /usr/bin/custom_service.sh
    
     [Install]
     WantedBy=multi-user.target
    
  4. Move the unit file to /etc/systemd/system and give it permissions:

     sudo mv <service_name>.service /etc/systemd/system/<service_name>.service
     sudo chmod 644 /etc/systemd/system/<service_name>.service
    
  5. Start the service:

     sudo systemctl start <service_name>
    
  6. Check the status of the service:

     sudo systemctl status <service_name>
    
  7. To enable service on machine startup when the system boots use:

     sudo systemctl enable <service_name>
    
  8. To stop and restart service use:

     sudo systemctl stop <service_name>
     sudo systemctl restart <service_name>
    

References:

  1. What is systemd?

  2. systemctl Commands: Restart, Reload, and Stop Service

  3. Vagrant templates

  4. Systemd service options