Bundle Exec with Custom Gemfile

When configuring unicorn for my rails app on an Ubuntu 14.04 server, an error suddenly occured to me. When running sudo service myapp restart, which is basically a unicorn script for start serving my app, it tells me the following message.

/home/ubuntu/.rvm/gems/ruby-2.1.3/gems/bundler-1.12.0/lib/bundler/runtime.rb:35:in `block in setup': You have already activated rack 1.6.4, but your Gemfile requires rack 1.5.5. Prepending `bundle exec` to your command may solve this. (Gem::LoadError)

After digging into this issue, I found that the my unicorn script is located at /etc/init.d/myapp, which uses global gems as default. Since it runs my app, it is more reasonable to make it use the Gemfile in my application project.

The command in the config file looks like this:

CMD="unicorn_rails -D -E production -c $APP_ROOT/config/unicorn.rb"

I replaced the unicorn_rails with bundle exec unicorn_rails to make sure it uses bundler. However, it tells me:

Could not locate any Gemfile

Thus it took me some time to find out that we can specify a Gemfile when using bundler, which is exactly a solution in this case. I added the BUNDLE_GEMFILE variable and it went well again.

CMD="bundle exec unicorn_rails -D -E production -c $APP_ROOT/config/unicorn.rb"

This variable can also be specified in command line:

BUNDLE_GEMFILE=/home/ubuntu/myapp/Gemfile bundle exec unicorn_rails

Hope this solve some others' issues too!