Search code examples
ruby-on-railsherokuredisresque

Redis connection error on Heroku


I have a Rails app which uses Resque for background jobs. This works fine locally, but after deploying to Heroku I get a connection error:

Redis::CannotConnectError (Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED)):

I see it tries to connect to localhost, which is not correct. I'm using the Heroku Redis :: Redis add-in and I have added the redis gem. This is how initializers.redis.rb looks like:

$redis = Redis.new(url: ENV["REDIS_URL"])

And this is my Procfile:

web: bundle exec puma -C config/puma.rb
resque: env TERM_CHILD=1 bundle exec rake resque:work QUEUE=* COUNT=1

In the config vars REDIS_URL is added. What is going wrong here?


Solution

  • It seems that when using Puma or Unicorn on Heroku, you need to add it also to the boot process. I'm using Puma, so I added this to config/puma.rb:

    on_worker_boot do
      # ...
      if defined?(Resque)
         Resque.redis = ENV["REDIS_URL"] || "redis://127.0.0.1:6379"
      end
    end
    

    Here is a more detailed explanation for both Puma and Unicorn: https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server https://devcenter.heroku.com/articles/rails-unicorn#caveats