Create linux service
Creating a simple Linux service involves writing a script, creating a service unit file, and then enabling and starting the service. Here is a step-by-step guide to creating a simple Linux service using systemd, the most common init system in modern Linux distributions.
- Create a script:
First, create a simple script that you want to run as a service. For example, create a script that writes the current date and time to a file every minute.
#!/bin/bash
while true
do
date >> /var/log/my_service.log
sleep 60
done
Save this script as /usr/local/bin/my_service.sh and make it executable:
sudo chmod +x /usr/local/bin/my_service.sh
Create a service unit file in /etc/systemd/system/. For example, create a file named my_service.service:
[Unit]
Description=My Simple Service
After=network.target
[Service]
ExecStart=/usr/local/bin/my_service.sh
Restart=always
User=nobody
[Install]
WantedBy=multi-user.target
Reload the systemd manager configuration to recognize the new service:
sudo systemctl daemon-reload
Enable the service to start on boot:
sudo systemctl enable my_service.service
Start the service immediately:
sudo systemctl start my_service.service
Verify that the service is running correctly:
sudo systemctl status my_service.service
This basic example demonstrates how to create a simple Linux service using systemd. The service script writes the date and time to a log file every minute, and the service unit file configures systemd to manage the script as a service.