How to Add and Manage Services in Linux: A Step-by-Step Guide

Adding services in Linux typically involves creating and managing systemd service units. Here's a step-by-step guide:


1. Create a Systemd Service File

Systemd service files are stored in /etc/systemd/system/ and have a .service extension.

Example: Creating a Custom Service

Let's say you have a script (/usr/local/bin/myscript.sh) that you want to run as a service.

Step 1: Create the Service File

Create a new service file using a text editor:

sudo nano /etc/systemd/system/myscript.service
        

Step 2: Add Service Configuration

Add the following content:

[Unit]
Description=My Custom Service
After=network.target

[Service]
ExecStart=/usr/local/bin/myscript.sh
WorkingDirectory=/usr/local/bin
Restart=always
User=root
Group=root

[Install]
WantedBy=multi-user.target
        

Step 3: Save and Exit

Save the file (CTRL+X, then Y, then Enter).


2. Reload Systemd

After creating the service file, reload systemd to recognize the new service:

sudo systemctl daemon-reload
        

3. Start the Service

Start your newly created service:

sudo systemctl start myscript
        

To check the status:

sudo systemctl status myscript
        

4. Enable the Service at Boot

To make the service start on system boot:

sudo systemctl enable myscript
        

To disable it from auto-starting:

sudo systemctl disable myscript
        

5. Restart or Stop the Service

To restart:

sudo systemctl restart myscript
        

To stop:

sudo systemctl stop myscript
        

6. View Service Logs

Use journalctl to see logs:

journalctl -u myscript -f
        

7. Remove the Service

To remove a service:

sudo systemctl stop myscript
sudo systemctl disable myscript
sudo rm /etc/systemd/system/myscript.service
sudo systemctl daemon-reload
        

Additional Service Management Commands

Command Desc

systemctl list-units --type=service List all active services

systemctl list-unit-files --type= service List all available services

systemctl restart <service> Restart a service

systemctl disable <service> Disable a service

systemctl enable <service> Enable a service to start at boot


要查看或添加评论,请登录

Venkatavelavan N.的更多文章

社区洞察

其他会员也浏览了