LoginSignup
7
6

More than 3 years have passed since last update.

systemdで/var/run配下にUNIX Socket用のディレクトリを切ったら落とし穴にハマった件と対処法

Posted at

動作確認環境

  • CentOS7のサーバ

※Ubuntu20.04も同じ実装なので同じくハマるかと思います

落とし穴にハマった流れ

やりたいこと

  • hogeというアプリケーションのAPIサーバを建てたい
    • フロントは nginxでリクエストを受けてアプリケーションに渡す
    • hogesystemdでデーモン化する
    • hogenginxからのリクエストを UNIX Socketで受け取る
      • UNIX Socket/var/run/hoge/hoge.sockとする

やったこと

  • /var/run/hogeディレクトリを作成する
    • パーミッションは hoge:hogeとする
  • hogenginxの各種設定ファイルを配置してデーモンを起動する
    • この時点で動いたことは確認できた
  • サーバを再起動する
  • 再びAPIを叩くと nginxBad Gatewayのエラーを返した
    • 調べてみると/var/run/hoge/hoge.sockがディレクトリごと無くなっていた

原因

  • CentOS7では /var/run配下が tmpfsになっており、サーバを再起動すると /var/run配下のファイルが消えてしまう
# /var/run は /run へのシンボリックリンク
$ ls -ld /var/run
lrwxrwxrwx. 1 root root 6 Jul 25  2019 /var/run -> ../run

# /run は tmpfs をマウントしている
$ mount | grep /run
tmpfs on /run type tmpfs (rw,nosuid,nodev,mode=755)

対処法

systemdのUnitファイルに RuntimeDirectoryの設定を追加する

tmpfiles.dMANページによると

原文
System daemons frequently require private runtime directories below /run to store communication sockets and similar.
For these, it is better to use RuntimeDirectory= in their unit files (see systemd.exec(5) for details), if the flexibility provided by tmpfiles.d is not required.
The advantages are that the configuration required by the unit is centralized in one place, and that the lifetime of the directory is tied to the lifetime of the service itself.
Similarly, StateDirectory=, CacheDirectory=, LogsDirectory=, and ConfigurationDirectory= should be used to create directories under /var/lib/, /var/cache/, /var/log/, and /etc/.
tmpfiles.d should be used for files whose lifetime is independent of any service or requires more complicated configuration.
日本語訳
システムデーモンは、通信ソケットなどを格納するために、/runの下にプライベートランタイムディレクトリを必要とすることがよくあります。
これらについては、tmpfiles.dによって提供される柔軟性が必要ない場合は、ユニットファイルでRuntimeDirectory =を使用することをお勧めします(詳細については、systemd.exec(5)を参照)。
利点は、ユニットに必要な構成が1か所に集中化されていること、およびディレクトリの存続期間がサービス自体の存続期間に関連付けられていることです。
同様に、/var/lib/、/var/cache/、/var/log/、および/etc/の下にディレクトリを作成するには、StateDirectory=、CacheDirectory=、LogsDirectory=、およびConfigurationDirectory=を使用する必要があります。
tmpfiles.dは、存続期間がサービスに依存しないか、より複雑な構成が必要なファイルに使用する必要があります。

とあるので、RuntimeDirectoryの設定を追加します。

また、今回はパーミッションを 0755としたいので以下の様に RuntimeDirectoryModeも設定します。

UNITファイルに追加した行
RuntimeDirectory=hoge
RuntimeDirectoryMode=0755

systemd.execMANページによると /runが起点となるため、フルパスではなく /run配下に作りたいディレクトリ名を指定します

参考リンク

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6