経緯
- Railsを動かしているElasticBeanstalkでメモリの消費量が増大している
- 定期的/一定量のメモリを消費したらアプリをリスタートしたい
注意事項
まずはRailsやpumaなどを最新にして、自アプリ以外が原因のメモリリークをなくしましょう
- っていうか自アプリのメモリリークも無くせるならなくしましょう!
puma_worker_killerって?
schneems/puma_worker_killer: Automatically restart Puma cluster workers based on max RAM available
- pumaのworkerを定期的/一定量のメモリを消費したらkillしてくれるgem
- メモリリーク対策によく使われる
方法
1.Gemfilesに追加
group :production do
gem 'puma_worker_killer'
end
2.設定ファイル(.ebextensions)にて、puma_worker_killerの設定をElasticBeanstalkに入れる
ElasticBeanstalkでは、設定ファイル(.ebextensions)により環境のカスタマイズができる
.ebextensions ディレクトリに、configファイルを置くと、それを読み込んでファイルの追加やコマンドの実行などをしてくれる
なので、ElasticBeanstalkのpumaの設定ファイルに、puma_worker_killer 用の設定を追加するコマンドを書く
- ./ebextensions/00_add_puma_extend_conf.config
files:
'/opt/elasticbeanstalk/support/conf/puma_extend_conf.rb':
mode: "000644"
owner: root
group: root
content: |
before_fork do
require 'puma_worker_killer'
PumaWorkerKiller.config do |config|
config.ram = 2048
config.frequency = 5
config.percent_usage = 0.98
config.rolling_restart_frequency = 24 * 60 * 60
config.reaper_status_logs = true
end
PumaWorkerKiller.enable_rolling_restart
PumaWorkerKiller.start
end
container_commands:
00_add_puma_extend_conf:
command: |
cat /opt/elasticbeanstalk/support/conf/puma_extend_conf.rb >> /opt/elasticbeanstalk/support/conf/pumaconf.rb
test: "test ! -e /home/ec2-user/add_puma_extend_conf_done"
01_add_puma_extend_conf_done:
command: "touch /home/ec2-user/add_puma_extend_conf_done"
test: "test ! -e /home/ec2-user/add_puma_extend_conf_done"
解説
files:
container_commands:
- デプロイ後に実行されるコマンド群を設定
- ソート順に実行される
/opt/elasticbeanstalk/support/conf/puma_extend_conf.rb
は、ElasticBeanstalk で参照されるpumaの設定ファイル
- そこに、
files:
で追加した、puma_worker_killerの設定を書いたファイルの内容を追加する
- その後に、空ファイル
/home/ec2-user/add_puma_extend_conf_done
を作成
test:
オプションは、戻り値が0以外の場合実行しなくするオプション
- 空ファイル
/home/ec2-user/add_puma_extend_conf_done
があったら実行しない
- 1回puma_worker_killerの設定が追加されたら、もう実行しないようにするため
デプロイ後、ログを見てみる
[30959] PumaWorkerKiller: Rolling Restart. 1 workers consuming total: 99.34765625 mb out of max: mb. Sending TERM to pid 13411.
[30959] PumaWorkerKiller: Consuming 99.34765625 mb with master and 1 workers.
適当なタイミングで再起動したり、メモリの残量をチェックしてくれている!