LoginSignup
11
11

More than 5 years have passed since last update.

EC2(AWS)で起動時にアプリを自動起動する

Posted at

背景

  • ec2-user(アプリによっては別ユーザ)にて、Railsアプリを起動していた。
  • 定期的にイメージのバックアップを作成する際に、インスタンスを停止、起動したいという要望があった
  • インスタンスを停止してから起動するとRailsアプリが起動されない。。。。
  • インスタンスの起動時に自動実行されるscriptでRailsアプリを起動させよう。

アプリ起動時に実行していたコマンドたち

$ sudo service nginx start                                   # rootでnginxを起動
$ RAILS_ENV=production bundle exec rails assets:precompile   # デプロイユーザでprecompile
$ RAILS_ENV=production bundle exec puma -C config/puma.rb    # デプロイユーザでpuma起動

自動起動scriptの作成

application-starter

#!/bin/sh
# chkconfig: 345 99 10
# description: start shell
case "$1" in
  start)
    service nginx start
    su -l ec2-user -c "sh /home/ec2-user/start.sh"
       ;;
  stop)
       echo "stop!"
       ;;
  *) break ;;
esac

start.sh

start.sh
#!/bin/sh
cd /home/ec2-user/application
RAILS_ENV=production bundle exec rails assets:precompile
RAILS_ENV=production bundle exec puma -C config/puma.rb

起動シェルの登録

$ sudo su -
# cd /etc/init.d/
# chmod +r application-starter
# chkconfig --add application-starter
# chkconfig application-starter on

AWSコンソールからインスタンスを停止 -> 起動を行う
ps コマンドでアプリが起動しているか確認

ハマったところ

rootユーザ以外で実行する処理は別シェルにしておき su -l user -c "Command"でuserを変えて実行する
su - userでユーザを変更しようとすると対話式でパスワード入力を待ってしまい、シェルが終わらない。。。

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