Having Cherokee playing well with RVM and Ruby on Rails

5 May 2010

Update: now it works with Rails 3.0.

Today I went down to try and have Cherokee working well with RVM. I wanted being able to switch the Ruby version with ease, in order to allow for a painless upgrading when patches are released upstream. More, I wanted to be able to create gemsets and such. Cherokee is fast as hell, and much easier to maintain than Apache.

After a little bit of fiddling, I came up with a nice and easy solution, which roughly goes like this:

  1. Create a rails user on your system. My advice is to lock it down with “passwd -l rails” after creation.
  2. If you installed any gems as root, it’s best to remove them. Then, follow the normal instructions to install rvm su-ing as the rails user. Compile and set as default a ruby instance of your choice (“rvm use –default ruby-1.8.7“, for example).
  3. Always logged in as the rails user, install any gem you may need. You can do this later, if you prefer. Test if your website starts manually, by calling script/server, or if it complains about missing gems.
  4. chmod -R your rails project to rails:rails. I keep my production sites under /var/www, but you can put ’em in /home/rails, for example.
  5. Use the standard wizard that comes with Cherokee to prepare the sources for your website.
  6. Under the “Interpreter command” text field of each of the three newly created sources, prepend the command that’s already there with (“/home/rails/spawner.sh“). For example: “/home/rails/spawner.sh example-website script/rails server -b 127.0.0.1 -e production -p 38161“. I omitted “/var/www/“, but you can put it there if you want.
  7. For each of the sources, set the user and the group the site will be served with to “rails“.
  8. Create a new file /home/rails/spawner.sh, which will do the simplest magic we need:
#!/bin/bash

if [ "$(whoami)" != "rails" ]; then
echo "Cannot run this script as root. You must sudo to the 'rails' user."
exit -1;
fi

export HOME="/home/rails"

if [[ -s "$HOME/.rvm/scripts/rvm" ]]; then
source "$HOME/.rvm/scripts/rvm";
fi

cd "/var/www/$1"
exec ${@:2}

Now, if someone of the Cherokee project would be so kind to fix that ugly “Bad gateway” error the first time you try to access a Rails site and the interpreter hasn’t been spawned yet, I’d be immensely grateful. 🙂

Advertisements