看了几个网上的教程,或多或少都有问题,实在是火大,遂决定整理一波。有问题的文章如下:
https://zhuanlan.zhihu.com/p/98804785
http://www.r9it.com/20180613/ubuntu-18.04-auto-start.html
问题一堆,常见的如.和-不区分、步骤不全等。
ubuntu 16.10之后已经不用initd(就是PID序号为1的那个进程)管理系统了,而systemd默认读取的是/lib/systemd/system/目录下的文件。所以我们配置一个新服务如下:
cd /lib/systemd/system gedit rc-local.service 如果rc-local.service不小心误删了,手动创建一下:touch rc-local.service。内容如下:
# 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.local is executable. [Unit] Description=/etc/rc.local Compatibility Documentation=man:systemd-rc-local-generator(8) ConditionFileIsExecutable=/etc/rc.local After=network.target [Service] Type=forking ExecStart=/etc/rc.local start TimeoutSec=0 RemainAfterExit=yes GuessMainPID=no # 添加的是以下内容,本行注释请注意移除。 [Install] WantedBy=multi-user.target Alias=rc-local.service注意到ExecStart=/etc/rc.local start行告诉我们开机自启的逻辑,所以需要在/etc/rc.local文件中进行配置你要的开机启动项(如果该文件不存在请创建):
#!/bin/sh -e # # rc.local # 以上三行以#开头的请不要移除,下面几行中文注释请移除 # 你的开机命令写在下方(exit 0的上方,注意空一行),例如我写两个autossh的命令 # 注意移除中文的注释 autossh -M 55555 -fCNR 2061:localhost:22 example@111.11.111.11 exit 0接着给该文件增加执行权限:
chmod a+x /etc/rc.local在/etc/systemd/system/创建一个到/lib/systemd/system/的软连接:
ln -s /lib/systemd/system/rc-local.service /etc/systemd/system/rc-local.service查看映射是否正确建立:
ls -al /etc/systemd/system/rc-local.service正常的话,显示如下:
lrwxrwxrwx 1 root root 36 10月 4 22:32 /etc/systemd/system/rc-local.service -> /lib/systemd/system/rc-local.service