Skip to main content

A Capistrano recipe for restarting Apache 2 (on Linux)

Capistrano is the rather excellent tool for automating Rails application deployment. But it can do a lot more than just uploading Rails applications to live webservers. It's scripts are basically Rake scripts and so have the full power of Ruby behind then so you can pretty much write code to do anything that you want.

I wanted a way to reload the configuration for my Apache2 web server running on my home Ubuntu server. I found a post on Mongrel and Capistrano 2.0 by John Ward which showed a very nifty way to create Capistrano tasks for variants of the same base command.

My adapted version for controlling Apache is:
namespace :apache do
[:stop, :start, :restart, :reload].each do |action|
desc "#{action.to_s.capitalize} Apache"
task action, :roles => :web do
invoke_command "/etc/init.d/apache2 #{action.to_s}", :via => run_method
end
end
end
Add this code to your config/deploy.rb. This will add four new tasks to Capistrano which you can use to restart or reload Apache:
cap apache:stop
cap apache:start
cap apache:restart
cap apache:reload
Technorati Tags: , , , , , , ,

Comments

Anonymous said…
Thanks!
Very elegant way to do :)
Anonymous said…
More generally, we could use this for a set of several services that we want to control remotly.
For example with apache and mysql:

# For each service...
{:apache => 'apache2', :mysql => 'mysql'}.each do |name, script|
namespace name do
# For each action...
[:stop, :start, :restart, :reload].each do |action|
desc "#{action.to_s.capitalize} #{name.to_s.capitalize}"
task action, :roles => :web do
run "/etc/init.d/#{script} #{action.to_s}"
end
end
end
end
Andrew Beacock said…
ngryman,

So what you are saying is if we have a control script that lives within /etc/init.d (and therefore obeys the rules of stop/start/(restart?)) then we can simply list them at the top and get the rest of the rake task to auto-generate the tasks.

I like your thinking!
feby artandi said…
very nice, thanks
This is really great!!
Very helpful indeed!! especially for those who encounter difficulty with regard to the services they offer.
Lethbridge SEO said…
I am having the hardest time with using Ubuntu server. My friend who recommended it to me has no problems at all, but I can't get full functionality, and when we both try to do some trouble-shooting, nothing ever comes of it. It is so frustrating!

But back to the topic, the Capistrano recipe looks like it's worth trying out.
THanks,
Angela
Greg Winn said…
Thanks, have been looking for this!