发生的问题
我在 ElasticBeanstalk 上运行的 Rails 项目的内存使用率很高。
从流程来看,彪马是主要因素。
为了释放内存,我们考虑过自动替换实例,但是ElasticIP的自动分配出现了问题,所以这次我们决定使用gempuma_worker_killer。
puma_worker_killer 官方页面
https://github.com/zombocom/puma_worker_killer
前提
- ElasticBeanstalk 环境(在 64 位 Amazon Linux 2/3.4.7 上运行的 Ruby 2.7)
- EC2 实例数:1(使用 ElasticIP)
- Puma 工人人数:2
程序
1.修改Gemfile
group :production do
gem 'puma', '5.6.4'
gem 'puma_worker_killer' #追加
end
$ bundle install
2.在config/puma.rb中添加设置
if ENV.fetch("RAILS_ENV") == "production"
# ElasticBeanstalkのpumaconf.rbのデフォルト設定
directory '/var/app/current'
threads 8, 32
workers %x(grep -c processor /proc/cpuinfo)
bind 'unix:///var/run/puma/my_app.sock'
stdout_redirect '/var/log/puma/puma.log', '/var/log/puma/puma.log', true
# PumaWorkerKiller設定
before_fork do
require 'puma_worker_killer'
PumaWorkerKiller.config do |config|
config.ram = 4096 # EC2インスタンスのメモリ量(MB)
config.frequency = 5 * 60 # 何秒ごとに現在のメモリ使用量を確認するか(5分ごと)
config.percent_usage = 0.80 # Pumaがメモリを何%使ったら再起動するか(アラート発砲が90%、他のプロセスもメモリを喰うことを考えて80%にする)
config.rolling_restart_frequency = 24 * 60 * 60 # 上記の設定とは別に、1日に1回は再起動する
config.reaper_status_logs = true # ログ出力(デバッグ用)
end
PumaWorkerKiller.start
end
end
3. 准备 Procfile
web: mkdir -p /var/app/current/tmp/pids && bundle exec puma -C /var/app/current/config/puma.rb
效果确认
这是在EB环境下查看puma.log的结果
cat /var/log/puma/puma.log | grep "PumaWorkerKiller"
使用 config.percent_usage 重新启动工作器
Worker 通过 config.rolling_restart_frequency 重启
CloudWatch 的内存利用率图表
卡点
1. EB环境下PumaWorkerKiller不启动
在默认的 ElasticBeanstalk 环境中,似乎 Puma 是使用 /opt/elasticbeanstalk/config/private/pumaconf.rb 设置启动的,而没有查看 config/puma.rb 设置。
结果虽然config/puma.rb中描述了设置,但PumaWorkerKiller并没有在EB环境启动,而是在本地测试启动。
我通过在根目录中创建Procfile 并使用config/puma.rb 启动Puma 来解决它。
此外,/opt/elasticbeanstalk/config/private/pumaconf.rb 中的默认设置也在/config/puma.rb 中进行了描述。
关于 Procfile
https://docs.aws.amazon.com/ja_jp/elasticbeanstalk/latest/dg/ruby-platform-procfile.html
2. pumaconf.rb 修改为.ebextensions 也无法加载PumaWorkerKiller
当我第一次学习使用/opt/elasticbeanstalk/config/private/pumaconf.rb 设置时,我尝试使用.ebextentions 将PumaWorkerKiller 设置添加到pumaconf.rb,但它没有工作,出现以下错误。
/opt/rubies/ruby-2.7.6/lib/ruby/site_ruby/2.7.0/rubygems/core_ext/kernel_require.rb:85:in `require': cannot load such file -- puma_worker_killer (LoadError)
puma/puma.log:[8772] WARNING hook before_fork failed with exception (NameError) uninitialized constant #<Class:#<Puma::DSL:0x0000000001df7130>>::PumaWorkerKiller
我找不到解决方案,最后我决定使用Procfile 和config/puma.rb。
原创声明:本文系作者授权爱码网发表,未经许可,不得转载;
原文地址:https://www.likecs.com/show-308622248.html