上次谈了如何开发rails的non browser app,本文将谈谈如何部署这类APP的问题
用于生产环境时,必须要考虑到如何将其部署和运行,最好的办法是让这个app作为daemon运行,并且可以通过capistrano自动运行。
1、Capistrano的基本用法-这里就不介绍了
2、让一个app能够daemon运行,首先在script下创建一个文件daemon,内容如下:
#!/usr/bin/env ruby
require File.expand_path("http://www.cnblogs.com/config/environment", __FILE__)
require 'daemons'
ENV["APP_ROOT"] ||= File.expand_path("#{File.dirname(__FILE__)}/..")
ENV["RAILS_ENV"] ||= "development"
ENV["RAILS_ENV_PATH"] ||= "#{ENV["APP_ROOT"]}/config/environment.rb"
script = "#{ENV["APP_ROOT"]}/#{ARGV[1]}"
pid_rep = "/tmp/myapp/pids"
begin
FileUtils.mkdir_p(pid_rep)
rescue
puts "pids stored in the diretory: "+pid_rep
end
Dir.chdir Rails.root
Daemons.run(script, dir_mode: :normal, dir: pid_rep)
3、修改Gemfile,增加一行:
require 'daemons'
4、运行bundle install
5、测试脚本:utils/test.rb
loop
sleep 60
puts "I am awake after 1 minute"
end
6、运行(阻塞当前shell)
script/daemon run utils/test.rb
7、daemon运行
script/daemon start utils/test.rb
8、stop daemon
script/daemon stop utils/test.rb
9、通过capistrano部署到生产环境,并且在服务器上daemon运行,修改config/deploy.rb,加入:
desc "run utils in daemon"
daemon_script = current_path+'/script/daemon'
production_env = 'RAILS_ENV=production '
namespace :deploy do
task :utils do
run production_env+daemon_script+" stop utils/test.rb"
run production_env+daemon_script+" start utils/test.rb"
end
end
10、运行cap deploy:utils
11、检验:在服务上运行ps -ef|grep test能够看到有test.rb进程