Capistrano to auto-deploy a Node.js app

4 Sep 2012

After figuring out for a while, `Capistrano` is still the best one to deploy any app to a production server.

Let's do some quick overview; Here is what `Capistrano` does:

  1. Login through SSH to your production server
  2. Re-link all necessary folders
  3. Restart your Node.js app

Here are the normal step:

  1. Install `Ruby, ``Rubygems`, and thengem install capistrano``
  2. Go to your production server, create the user `deploy, and set all SSH keys (for your local computer to access ``deploy` and fordeploy`` to access your source-control server)
  3. Create the folder `/somethingand ``chown deploy:deploy /something```
  4. Go to your project folder and type `capify .`
  5. Install `node, ``npm`, andforever``
  6. Put this in your `config/deploy.rb`
set :application, "something" set :repository, "git@bitbucket.org:something/something.git" set :deploy_to, "/#{application}" set :scm, :git set :use_sudo, false set :user, "deploy" set :executable_file, "index.js" role :app, "YOUR_IP" # This may be the same as your `Web` server namespace :deploy do task :start do ; end task :stop do ; end task :restart, :roles => :app, :except => { :no_release => true } do begin run "cd #{release_path} && forever stop #{executable_file}" rescue end run "cd #{release_path} && forever start #{executable_file}" end end namespace :npm do task :create_symlink, :roles => :app do shared_dir = File.join(shared_path, 'node_modules') release_dir = File.join(current_release, 'node_modules') run("mkdir -p #{shared_dir} && ln -nfs #{shared_dir} #{release_dir}") end task :install, :roles => :app do npm.create_symlink shared_dir = File.join(shared_path, 'node_modules') run "cd #{release_path} && npm install" end end after "deploy:update_code" do npm.install end

This deployment script gets a new source code, do the `npm install`, and restart the server for you.

Now you can deploy by typing `cap deploy`. (Do not forget to push your latest code to the source-control server first).

You're welcome!

Give it a kudos