LoginSignup
1
1

More than 3 years have passed since last update.

Go言語で作成した実行ファイルをEC2でデーモンとして実行する

Last updated at Posted at 2020-11-30

概要

Go言語でbuildした実行ファイルをEC2上に配置しdeamon化します。
そうして、EC2の起動時に自動的にGoでビルドしたWebサーバを実行させます。

経緯

Go言語+GinでビルドしたWebサーバをEC2上で構築していたのですが、
EC2の起動時に自動実行されなかったのでいろいろと試した結果、デーモン化しinit.dで自動起動させました。

1 ビルドした実行ファイルのデーモン化


ディレクトリ
/etc/systemd/system/サービス名.service

[Unit]
Description=説明文

[Service]
User=root
Group=root
WorkingDirectory=ディレクトリ
ExecStart=ディレクトリ/実行ファイル名
Restart=always
KillMode=process

[Install]
WantedBy=multi-user.target

サービスの確認

systemctl status サービス名.service
systemctl start サービス名.service
systemctl stop サービス名.service

上記でサービスの起動が出来たらデーモン化は完了です。

2. init.dでサービスの自動起動を設定


ディレクトリ
/etc/int.d/app_start
--------------init.d 内容-------------------------
#!/bin/sh
# chkconfig: 2345 99 10
# description: deamon wakeup scrupt

case "$1" in
 start)
       date >> /home/user/start.txt
       echo "start!" >> /home/user/app_start.log
       sudo sh /home/user/scripts/application_start_server.sh
       ;;
 stop)
       echo date >> /home/user/app_stop.log
       sudo sh /home/user/scripts/application_stop_server.sh
       ;;
  *) break ;;
esac

application_start_server.sh の部分は直接コマンドを書いても良いですし、
今回はシェルスクリプトを実行させました。
(サービスの起動・停止時に時間をファイルに出力しています。)

3 確認

EC2を再起動しサービスが正常に起動していれば完了です。

所感

インスタンスの再起動は物理マシンの起動と挙動が違うので、
その辺りが原因でバッチ処理ではうまく動かなかったのだと考えています。

1
1
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
1
1