Capistrano: 自动化部署的利器 thin+nginx 自动化部署
1.添加Gemfile (bundle install)
group :development gem 'capistrano', '2.12.0' gem 'capistrano-rbenv', '1.0.1' end
2.运行 $ capify . (会生成两个文件)
$ capify .
capify .
[skip] './Capfile' already exists
[skip] './config/deploy.rb' already exists
[done] capified!
会生成两个关键性的文件: Capfile
, config/deploy.rb
下面是一个完整的 部署脚本( config/deploy.rb )的例子, 修改其中的 用户名,端口号, 目标服务器的域名 , 服务器的启动方式, 就可以直接运行了.:
# -*- encoding : utf-8 -*-
require 'capistrano-rbenv'
load 'deploy/assets'
SSH_USER = '你的用户名'
SSH_PORT = '你的端口号'
server = "目标服务器的域名或者ip"
FOLDER_IN_REMOTE_SERVER = '远程服务器上的目标文件夹'
ssh_options[:port] = SSH_PORT
set :rake, "bundle exec rake"
set :application, "app name"
set :repository, "."
set :scm, :none
set :deploy_via, :copy
role :web, server
role :app, server
role :db, server, :primary => true
role :db, server
set :deploy_to, FOLDER_IN_REMOTE_SERVER
default_run_options[:pty] = true
# change to your username
set :user, SSH_USER
namespace :deploy do
task :start do
run "cd #{release_path} && bundle exec thin start -C config/thin.yml"
end
task :stop do
run "cd #{release_path} && bundle exec thin stop -C config/thin.yml"
end
task :restart, :roles => :app, :except => { :no_release => true } do
db_migrate
stop
sleep 2
start
end
task :db_migrate do
run "cd #{release_path} && bundle install"
run "cd #{release_path} && bundle exec rake db:migrate RAILS_ENV=production"
end
namespace :assets do
task :precompile do
#run "bundle install"
#run "cd #{release_path} && bundle exec rake RAILS_ENV=production RAILS_GROUPS=assets assets:precompile "
end
end
end
desc "Copy database.yml to release_path"
task :cp_database_yml do
puts "=== executing my customized command: "
run "cp -r #{shared_path}/config/* #{release_path}/config/"
run "ln -s #{shared_path}/files #{release_path}/public/files"
# 因为在开发机器上会存在这个文件夹,所以需要先把它删掉,再 ln
run "rm #{release_path}/public/uploads -rf"
run "ln -s #{shared_path}/public/uploads #{release_path}/public/uploads"
puts "=== done (executing my customized command)"
end
before "deploy:assets:precompile", :cp_database_yml
#after "deploy", "deploy:restart"
第一次运行时,要先 配置好目标服务器上的文件夹.
$ cap deploy:setup
注意: 这里让它创建基本的目标文件夹目录层次就可以:
/opt/app:
current (这是个软链接 soft link, )-> /opt/app/releases/20150518030114/
releases/
shared/
assets
config
files
log
pids
public
system
为 shared
目录下,增加各种配置文件,它们只需要被配置一遍。例如:
config/thin.yml # 服务器的配置
config/database.yml # 数据库的配置
config/log4r.yml # 日志文件的配置
config/settings.yml # 系统的配置
配置好ruby环境, mysql, thin, nginx 等
开始部署
$ bundle exec cap deploy.
这个命令会执行下面的过程:
- 准备启动服务器:
- 安装各种新增的rubygem
- 做必要的数据库迁移
- 配置各种文件
- 修改上传文件夹的softlink
- 其他,每次使用裸代码做部署的时候,都要人肉做的事情. (修改保存日志的路径, 修改 rails server的配置, )
- 编译,压缩 js/ css
- 重启 服务器(
$ nginx -s reload
,$ kill -9 xxx
,$ thin start -C config/thin.yml
)
配置h5项目
1,添加Gemfile
然后bundle
2.添加deploy文件 capify .
3.添加deploy.rb里面脚本内容
4. bundle exec cap deploy:setup
5. bundle exec cap deploy
6.到远程配置Nginx