Centos8 程序开机自动启动

发表于 2023-02-05

1、rc-local 服务

添加命令

编辑文件 /etc/rc.local 或者 /etc/rc.d/rc.local/etc/rc.local/etc/rc.d/rc.local 文件的一个符号链接。

vim /etc/rc.local

添加相应的命令到文件末尾,得到如下文件结果。

#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local
# 添加相应命令
/usr/local/nginx/sbin/nginx

/etc/rc.d/rc.local 文件加入可执行属性。

[root@hostname]# chmod +x /etc/rc.d/rc.local
[root@hostname]# ll /etc/rc.d/rc.local 
-rwxr-xr-x 1 root root 530 Mar 11 14:44 /etc/rc.d/rc.local

配置 rc.local 服务

编辑 rc.local 服务描述文件 rc-local.service

vim /usr/lib/systemd/system/rc-local.service

rc.local 文件如下,Install 模块最开始是没有的,是编辑添加的,否则服务启动时会报错。

#  SPDX-License-Identifier: LGPL-2.1+
#
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.d/rc.local is executable.
[Unit]
Description=/etc/rc.d/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.d/rc.local
After=network.target

[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no

# 需要添加 Install 模块,好启动 rc.local 服务
[Install]
WantedBy=multi-user.target

启动 rc-local 服务

systemctl daemon-reload
systemctl start rc-local
systemctl enable rc-local

注意

最好创建自己的systemd服务或udev规则来在引导期间运行脚本,而不是使用这个文件。

rc-local 服务在文件 rc.local 添加的命令不需要 nohup。 rc.local 不依赖于终端,所以不需要使用 nohup。

2、编辑服务

创建服务描述

创建服务描述文件。

vim /lib/systemd/system/frpc.service

写入描述信息。

[Unit]
Description=frpc service
After=network.target syslog.target
# Wants 为"弱依赖"关系,即如果依赖服务启动失败或停止运行,不影响当前服务。
# Requires 为"强依赖"关系,即如果依赖服务启动失败或异常退出,那么当前服务也必须退出。
Wants=network.target

[Service]
Type=simple
# 启动服务的命令
ExecStart=/usr/local/frp/frpc -c /usr/local/frp/frpc.ini
# 设置启动失败后重试
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target

启动服务并设置自启

创建服务并启动服务设置自启。

systemctl daemon-reload
systemctl start frpc
systemctl enable frpc
systemctl status frpc