SystemdでGo言語のウェブアプリをデーモン化して永続化する方法

GoのアプリをAWSのEC2にあげて

go run main.go

とかでアプリをあげるけど、それを永続化してデーモン化して仮に落ちても自動で再起動するようなことをしたかった。

場所

$ cd /etc/systemd/system
$ vi app.service

コード

[Unit]
Description=App

[Service]
ExecStart=/bin/bash -c 'go run main.go'
WorkingDirectory=/home/ubuntu/go/src/html/
Restart=always
Type=simple
User=ubuntu

[Install]
WantedBy=multi-user.target

ポイント

プロセスの自動再起動

Restart=always

実行

$ sudo systemctl daemon-reload
$ sudo systemctl start app.service
$ sudo systemctl status app.service

動いてることを確認

m$ sudo systemctl status app.service
● app.service - App
   Loaded: loaded (/etc/systemd/system/app.service; disabled; vendor preset: enabled)
   Active: active (running) since Thu 2019-10-24 21:59:06 UTC; 3min 31s ago
 Main PID: 17638 (go)
    Tasks: 15 (limit: 547)
   CGroup: /system.slice/app.service
           ├─17638 go run main.go
           └─17683 /tmp/go-build125150235/b001/exe/main

Oct 24 21:59:06 ip-10-0-56-179 systemd[1]: Started App.
Oct 24 21:59:11 ip-10-0-56-179 bash[17638]: Now listening on: https://localhost:8080
Oct 24 21:59:11 ip-10-0-56-179 bash[17638]: Application started. Press CTRL+C to shut down.

追記

$ sudo systemctl list-unit-files --type=service | grep app
app.service                                    disabled 

disabledでもどうやら問題なく動くようだ

関連

[Systemdでウェブアプリをデーモン化して永続化する最良な方法](https://off.tokyo/blog/systemd%e3%81%a7%e3%82%a6%e3%82%a7%e3%83%96%e3%82%a2%e3%83%97%e3%83%aa%e3%82%92%e3%83%87%e3%83%bc%e3%83%a2%e3%83%b3%e5%8c%96%e3%81%97%e3%81%a6%e6%b0%b8%e7%b6%9a%e5%8c%96%e3%81%99%e3%82%8b%e6%9c%80/)

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事