简介

以前,如果想要建立服务系统,就得要到 /etc/init.d/下面去建立相对应得bash脚本来完成。现在在systemd环境下面,想要设置相关的服务启动环境,那么该如何处理呢? 系统服务的管理是通过systemd来完成的,而systemd的配置文件大部分放置于/lib/systemd/system目录中,但是官方文档指出,该目录的文件主要是原本软件所提供的设置,建议不要修改,而要修改的位置应该放置于/etc/systemd/system/目录中。举例如下:

主要步骤

  1. ls /lib/systemd/system 你可以看到有很多启动脚本,其中就有我们需要的 rc.local.service,
    使用 cat /lib/systemd/system/rc.local.service
    其内容如下:
#  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.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
  1. 自己创建/etc/rc.local这个文件的, 因为debian10默认是没有,使用vim /etc/rc.local创建,里面的内容是我复制的,主要就是把第一句(#!/bin/sh -e) 和 最后一句(exit 0)写进去即可。
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
exit 0
  1. 让新建文件具有x权限,这个服务才能真的运行。

    sudo chmod +x /etc/rc.local
  2. 前面我们说 systemd 默认读取 /etc/systemd/system下的配置文件, 所以还需要在 /etc/systemd/system目录下创建软链接

    ln -s /lib/systemd/system/rc.local.service /etc/systemd/system/
  3. 把需要启动的脚本编辑到rc.local脚本中

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

sleep 10
mount -t nfs 192.168.10.9:/mnt/user/Media /mnt/disk0

// 启动脚本路径
// 注意: 一定要将命令添加在 exit 0之前
exit 0

Ubuntu 20.04开机自启动

配置 rc-local 服务

sudo cp /usr/lib/systemd/system/rc-local.service   /etc/systemd/system/            #复制 rc-local.service 文件

新建 rc.local 文件

sudo touch /etc/rc.local
sudo chmod 777 /etc/rc.local
sudo echo '''#!/bin/bash''' >> /etc/rc.local

在 rc.local 文件中加入自己想要开机自启的程序,以你自己的程序路径为准,只需将文件路径加入到 rc.local 即可

/opt/sipserver/minisipserver-cli &

设置开机自启动

sudo systemctl start rc-local
sudo systemctl enable rc-local