コンテンツにスキップ

起動時にプログラムを実行する(rc.localからの置き換え)

CentOS 6以前のマシンで起動時にプログラムを実行するようにrc.localに登録していましたが、AlmaLinux8はinit.dではなく、systemdが採用されています。(Systemd採用はCentOS 7からになります。) AlmaLinuxで同じことするための手法は2つあります。

rc.localを使い続ける

AlmaLinux /etc/rc.d/rc.localをcatすると、こんなコメントが記載されています。

#!/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 constrast 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.

rc.localをそのまま使うのであれば、rc.localに実行権限をつけるとブート時に実行されます。 推奨は、このファイルを使用する代わりに、systemdのサービスとして独自に定義しましょうという内容です。

systemdのやり方に置き換える

(1) /etc/systemd/systemの下に、拡張子.serviceのテキストファイルを作り、以下の内容を書きます。(例えば/etc/systemd/system/my-script.service)

[Unit]
Type=simple ←プロセスの起動タイプ。
Description=my-script shell   ←サービスの説明。
After=postgresql.service ←自分が起動する前に起動していてほしいサービスを書く。network.targetなど

[Service]
ExecStart=/bin/bash /my-script.sh ←実行したいプログラム

[Install]
WantedBy=multi-user.target ←どのターゲットで動かすか(マルチユーザー)

my-script.shは、起動したら常駐するようなタイプのシェルを想定しています。

(2) systemdをリロードして変更を適用します。

sudo systemctl reload-daemon

(3) OS起動時に自動起動するように設定します。

sudo systemctl enable my-script.service

(4) サービスを開始してみます。スクリプトが実行されるはずです。

sudo systemctl start my-script.service