capistrano 和 cron 中的 Rake 任务使用了错误的 ruby 版本

Rake tasks in capistrano and cron use wrong ruby version

我需要在部署过程中执行一个 rake 任务。为此,我在部署命名空间中有一个任务:

desc 'Start Telegram server'
task :start_telegram do
  on roles(:app) do
    puts "Current path: #{release_path}"
    within release_path do
      with rails_env: fetch(:rails_env) do
        execute :nohup, "bundle exec rake bot:start_poller > #{shared_path}/log/telegram.log 2>&1 & echo $! > #{shared_path}/tmp/pids/telegram-server.pid"
      end
    end
  end
end

是这样执行的:after :stop_telegram, :start_telegram。日志文件的输出是:

/var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler/spec_set.rb:87:in `block in materialize': Could not find nokogiri-1.10.3 in any of the sources (Bundler::GemNotFound)
        from /var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler/spec_set.rb:81:in `map!'
        from /var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler/spec_set.rb:81:in `materialize'
        from /var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler/definition.rb:170:in `specs'
        from /var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler/definition.rb:237:in `specs_for'
        from /var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler/definition.rb:226:in `requested_specs'
        from /var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler/runtime.rb:108:in `block in definition_method'
        from /var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler/runtime.rb:20:in `setup'
        from /var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler.rb:107:in `setup'
        from /var/lib/gems/2.3.0/gems/bundler-2.0.2/lib/bundler/setup.rb:20:in `<top (required)>'
        from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'

rbenv ruby 版本是 2.5.3,ruby -v 给我 ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-linux],我不明白为什么要查看 /usr/lib/gems/2.3.0。当 cron 执行 rake 任务时也会发生同样的情况。有什么想法可能是错误的吗?先谢谢了。

编辑: 如果我在服务器上手动执行它:RAILS_ENV=production nohup bundle exec rake bot:start_poller > /home/deployer/apps/aws-rails/www/shared/log/telegram.log 2>&1 & echo $! > /home/deployer/apps/aws-rails/www/shared/tmp/pids/telegram-server.pid,一切正常。

如果你想让 Capistrano 使用你的 rvm 版本那么你需要使用 capistrano/rbenv gem

# Capfile
require 'capistrano/rbenv'


# config/deploy.rb
set :rbenv_type, :user # or :system, depends on your rbenv setup
set :rbenv_ruby, '2.4.2'

有关详细信息,请查看下面的 link

https://github.com/capistrano/rbenv

要将 rbenv 与 crons 一起使用,请将以下内容添加到您的 bashrc

if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

https://benscheirman.com/2013/12/using-rbenv-in-cron-jobs/

我找到了解决办法,这个$HOME/.rbenv/bin/rbenv exec应该加上,所以,最后,可执行命令应该是这样的:execute :nohup, "$HOME/.rbenv/bin/rbenv exec bundle exec rake bot:start_poller > #{shared_path}/log/telegram.log 2>&1 & echo $! > #{shared_path}/tmp/pids/telegram-server.pid"