1 ubuntu18.04後啟動的原理變更
ubuntu-16.10 開始不再使用initd管理系統,改用systemd,systemd 就是用 systemctl 指令來替換了 service 和 chkconfig 的功能。
以前啟動 XXX服務用指令:
sudo service XXX start
現在改用:
sudo systemctl start XXX.service
開機啟動比以前複雜一些。systemd 預設是讀取 /etc/systemd/system 下的配置檔案,該目錄下的檔案會連結/lib/systemd/system/下的檔案。執行 ls /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
該配置檔案主要分為3個部分:
- [Unit] 段: 啟動順序與依賴關系
- [Service] 段: 啟動行為,如何啟動,啟動類型
- [Install] 段: 定義如何安裝這個配置檔案,即怎樣做到開機啟動
可以看到,預設的配置檔案中少了 Install 段,也就沒有定義如何做到開機啟動,是以顯然這樣配置是無效的。 是以我們的思路就是在後面幫他加上 [Install] 段。之後在rc.local中添加啟動腳本相關資訊,調試後重新開機 測試即可。
2 設定開機啟動腳本流程
@1 添加install字段
預設配置檔案為:
# 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
添加install字段,添加後,配置檔案為:
[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
@2 之後編輯檔案/etc/rc.local (沒有則建立)
把你需要啟動腳本寫入 /etc/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.
echo "log test" > /usr/local/test.log
#添加需要開機啟動的腳本指令集合
exit 0
之後 添權重限,如下所示:
sudo chmod +x /etc/rc.local
@3 建立軟連結
systemd 預設讀取 /etc/systemd/system 下的配置檔案, 是以還需要在 /etc/systemd/system 目錄下建立軟連結,如下所示:
ln -s /lib/systemd/system/rc.local.service /etc/systemd/system/
@4 重新開機系統測試開機腳本是否生效
可以通過列印日志的方式,比如:
echo "test log..." > /usr/local/test.log
也可以直接看執行結果。