Linuxを運用していて、サーバー起動時にコマンド実行できれば楽ではないでしょうか?
Windowsにはスタートアップというものがありますが、Linuxでも可能です。
という事でLinuxサーバーの起動時にコマンドを実行する方法を、現役エンジニアの筆者が例を元に教えます。
筆者はWindowsサーバーやLinuxサーバーの運用構築を11年以上おこなってきました。その経験を元に知識を公開していきます!
windowsのスタートアップのようなことをLinuxでしたい方は、この記事を読んで下さい。
Linuxで起動時にコマンドを実行する方法

Linuxで起動時にコマンド実行する方法は「/etc/rc.local」ファイルにコマンドを追記する事です。
起動時に「/etc/rc.local」ファイルに記入されたコマンドを、root権限で実行してくれます。
実際に「/etc/rc.local」ファイルの中身を見てみます。
[root@localhost ~]# cat /etc/rc.local
#!/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 contrast 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.
touch /var/lock/subsys/local
この最終行に起動時実行したいコマンドを追記していきます。
viエディタで追記していきます。
vi /etc/rc.local
viエディタで最終行に行くには「G」を押して、「o」で編集モードに変更して記入します。

以下のコマンドを追記しました。
echo start >> /var/log/startup.log
date >> /var/log/startup.log
echo finish >> /var/log/startup.log
「esc」を押してコマンドモードにしてから「:wq」でファイルを保存してviエディタを終了します。

Linuxサーバーを再起動してみます。
shutdown -r now
Linuxサーバーが立ち上がってきたら以下のコマンドでログを確認します。
cat /var/log/startup.log
すると結果は以下となりました。
[root@localhost ~]# cat /var/log/startup.log
start
2024年 5月 4日 土曜日 17:39:46 JST
finish
起動時にコマンドが実行されています。
起動時にコマンドが実行されていない場合の原因と対処法

Linuxサーバーの起動時にコマンドが実行されずログに何も記述されない原因は、「/etc/rc.local」が実行されていない事です。
解決方法としては権限をつける事です。
「/etc/rc.local」ファイルは「/etc/rc.d/rc.local」のリンクになっています。
本体の「/etc/rc.d/rc.local」の権限をlsコマンドで見てみます。

ls -l /etc/rc.d/rc.local

rootに実行権限が付与されていません。
以下のLinuxコマンドで、rootユーザーに実行権限を付与します。
chmod 744 /etc/rc.d/rc.local
もう一度権限を確認します。

rootユーザーに実行権限が付与されました。
これでLinuxサーバー起動時にコマンドが実行されます。
Linuxで起動時にシェルスクリプトを実行する方法

Linuxサーバー起動時にシェルスクリプトを実行したい場合もあると思います。
そんな時は「/etc/rc.local」ファイルに、シェルスクリプトを実行するコマンドを記入するだけです。
sh シェルスクリプトのパス
実際にviエディタで下の1行を記述します。
シェルスクリプトを「/opt/shell/startup.sh」に準備します。内容は以下の通りです。
echo startupでshellscript実行 >> /var/log/startup.log
それでは「/etc/rc.local」ファイルに下の一行を追加します。
sh /opt/shell/startup.sh
これで再起動してみます。
shutdown -r now
Linuxサーバーが立ち上がってきたら以下のコマンドで確認します。
[root@localhost ~]# cat /var/log/startup.log
startupでshellscript実行
Linux起動時にシェルスクリプトに書いたコマンドが、実行されている事が確認できました。
まとめ:Linuxで起動時にコマンドを実行する方法

Linuxで起動時にコマンド実行する方法は「/etc/rc.local」ファイルにコマンドを追記する事です。
root権限でコマンドを実行できます。
シェルスクリプトを実行する事も可能。やり方はシェルスクリプトを準備して「/etc/rc.local」にシェルを実行するコマンドを記述する。
起動時にコマンド実行されない場合は、「/etc/rc.local」のリンク先の「/etc/rc.d/rc.local」ファイルにrootユーザー実行権限を与える。