On a linux server, software is generally started directly using commands, such as ./nginx java -jar xxx.jar. If you want to start it in the background, you can use the nohup command.
However, if there is a power outage or other system reboot, the service will not start automatically.
To enable automatic startup on boot, using systemd to manage services is a good choice.
1. Writing the Configuration File
Taking the configuration file for the nginx service as an example.
# Core Concept: Unit - Metadata and Dependencies
[Unit]
# Description of the service, used for display in commands like systemctl status.
Description=nginx
# Defines which services this service should start after. This does not constitute a strong dependency, just an adjustment of the startup order.
After=network.target
# Service Configuration
[Service]
# Defines the type of process startup, very important!
Type=forking
# PID location set in nginx.conf
PIDFile=/var/run/nginx.pid
# Command to execute before ExecStart.
ExecStartPre=/usr/local/nginx/sbin/nginx -t
# Command and parameters executed when starting the service. This is required.
ExecStart=/usr/local/nginx/sbin/nginx
# Command executed when using systemctl reload, usually to reload the service configuration (e.g., send HUP signal)
ExecReload=/usr/local/nginx/sbin/nginx -s reload
# Command executed when using systemctl stop, for gracefully stopping the service. If not specified, Systemd will send SIGTERM signal directly to the main process.
ExecStop=/usr/local/nginx/sbin/nginx -s quit
# Installation Information
[Install]
# The most commonly used option. Specifies which "target" this service is "wanted" by. When using systemctl enable, a symbolic link will be created to the corresponding .wants directory.
# For example, WantedBy=multi-user.target means to enable this service in multi-user command line mode.
WantedBy=multi-user.target
We can simply modify the command path or configuration file path in the file.
Name the file nginx.service and place it in the /usr/lib/systemd/system/ directory.
2. Loading the Configuration
After writing the file, it does not take effect immediately; we need to use a command to let systemd load our written configuration.
sudo systemctl daemon-reload
3. Starting and Stopping the Service
sudo systemctl start nginxto start the servicesudo systemctl stop nginxto stop the servicesudo systemctl restart nginxto restart the service
4. Enabling Automatic Startup
Enable the service to start automatically on boot
sudo systemctl enable nginx