
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でもどうやら問題なく動くようだ