Ubuntu18.04 開機自啟動(需要 sudo 權限)


前言

ubuntu作為服務器使用時,常常需要在機器重啟時能自動啟動我們開發的服務。

Ubuntu 18.04不再使用initd管理系統,改用systemd,包括用systemctl命令來替換了service和chkconfig的功能。

systemd 默認讀取 /etc/systemd/system 下的配置文件,該目錄下的文件會鏈接/lib/systemd/system/下的文件。

不同於以往的版本,ubuntu18.04默認不帶/etc/rc.local文件,我們需要通過配置來讓rc.local.service生效。

然后我們就可以像以前那樣,直接把啟動腳本寫入/etc/rc.local文件,這樣機器啟動時就會自動運行它。

正文

以下操作最好在 root 賬號權限下操作

1. 檢查源文件 rc-local.service

檢查系統目錄/lib/systemd/system/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】,添加后的內容為:

#  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

這里我們可以看到添加了這些內容

####  需要自己添加
[Install]
WantedBy=multi-user.target
Alias=rc-local.service

2. 檢查 軟鏈接 rc-local.service

systemd 默認讀取 /etc/systemd/system 下的配置文件,該目錄下的文件會鏈接 /lib/systemd/system/下的文件。

查看 /etc/systemd/system 目錄下是否有 rc-local.service 文件,如果有,確認是否為 /lib/systemd/system/ 目錄下的軟鏈接

如果沒有則創建軟連接

ln -s /lib/systemd/system/rc-local.service /etc/systemd/system/rc-local.service

3. 創建 /etc/rc.local 腳本文件

rc.local 文件默認沒有創建,我們直接創建並賦值最高權限

sudo touch /etc/rc.local 
chmod 777 /etc/rc.local 

在 /etc/rc.local 里面我們就可以寫入我們想讓服務器開機時運行的命令,比如 echo "Hello Shuiche" > /usr/local/text.log

4. 啟用rc.local腳步

這里需要注意,在啟用腳步時,必須保證腳步有內容,並且是一個可執行腳步。不然會啟用失敗

sudo systemctl enable rc-local

5. 啟動服務並查看狀態

sudo systemctl start rc-local.service
sudo systemctl status rc-local.service

6. 重啟機器驗證

reboot


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM