Golang のアプリをデーモン化して起動する(CentOS)
Go でサービスを CentOS 7 でデーモン化する方法。今回は apple というユーザーが irohabook というアプリを作るときの流れをまとめる。
前提
プロジェクトのパス
/home/apple/go/src/irohabook
バイナリ
/home/apple/go/src/irohabook/irohabook
/home/apple/go/src/irohabook には main.go などがあり、そこでビルドして irohabook というバイナリができているとする。
Golang のアプリは一つのバイナリだけで動くことはほとんどない。テンプレートを読むこむアプリは次のようにデーモン化する。わざわざ supervisord を使う必要はない。
サービスファイルを作る
/etc/systemd/system/ にサービスファイルを作る。例えば irohabook.service として、そこに次のテキストを書く。
[Unit]
Description = irohabook
[Service]
User = root
Type = simple
ExecStart = /home/apple/go/src/irohabook/irohabook
WorkingDirectory = /home/apple/go/src/irohabook
Restart = always
[Install]
WantedBy = multi-user.target
このファイルは
/etc/systemd/system/irohabook.service
である。
設定の更新
ファイルを作ったら、あるいは更新したら、次のコマンドでシステムを更新する。
systemctl daemon-reload
自動起動の設定
サービスを自動起動するようにする。
sudo systemctl enable irohabook
起動
あとは起動して終わり。
sudo systemctl start irohabook
これでアプリがデーモン化される。
opt にコピーする…必要はない
Golang の実行ファイルはテンプレートを使うため、ディレクトリを WorkingDirectory で設定しないとデーモン化は失敗する。
ブログなどでバイナリを opt などにコピーしているが、する必要はない。バイナリだけをコピーしてもアプリは(サービスから)起動することはない。