配置 Capistrano 脚本

参考:Deploying Rails app using Nginx, Puma and Capistrano 3

进入 Rails app 所在的目录,先从 master 分支 git checkout -b config-capistrano ,再开始配置 capistrano 脚本。

安装 Cap gems

Gemfile 文件增加 cap 部署相关的 gems,并且把 puma 版本升级到 4,因为 capistrano3-puma 要求 puma 版本至少是 4.0.0。

# ...
gem 'puma', '~> 4.2.1'
# ...

group :development do
  # Remote multi-server automation tool
  # https://github.com/capistrano/capistrano
  gem "capistrano", "~> 3.11.1", require: false

  # RVM support for Capistrano v3
  # https://github.com/capistrano/rvm
  gem "capistrano-rvm", "~> 0.1.2", require: false

  # Rails specific Capistrano tasks
  # https://github.com/capistrano/rails
  gem "capistrano-rails", "~> 1.4.0", require: false

  # Bundler support for Capistrano 3.x
  # https://github.com/capistrano/bundler
  gem "capistrano-bundler", "~> 1.6.0", require: false

  # Puma integration for Capistrano 3
  # https://github.com/seuros/capistrano-puma
  gem "capistrano3-puma", "~> 4.0.0", require: false

  # Remote rails console for capistrano
  # https://github.com/ydkn/capistrano-rails-console
  gem "capistrano-rails-console", "~> 2.3.0", require: false

  # A collection of capistrano tasks for syncing assets and databases
  # https://github.com/sgruhier/capistrano-db-tasks
  gem "capistrano-db-tasks", "~> 0.6", require: false

  # Run any rake task on a remote server using Capistrano
  # https://github.com/sheharyarn/capistrano-rake
  gem "capistrano-rake", "~> 0.2.0", require: false
end

每个 gem 的用途,自行访问对应的 GitHub 仓库查阅。

配置 Capfile

cap install 命令会执行以下操作:

编辑 Capfile,将其替换为以下内容。

编辑 config/deploy.rb 文件,修改为一下内容。根据你的实际 repo 地址,修改 repo_url 的值。

配置 production.rb 文件

修改 config/deploy/production.rb 文件,根据实际情况替换 app_url 和 IP 地址为你服务器的值。

修改完毕后,git add . 然后 git commit -m "Config capistrano" ,提交本次修改内容。再 git push origin config-capistran ,把改动推送到 GitHub 。

确保服务器的数据库已经创建

参考:Creating user, database and adding access on PostgreSQL

如果你是跟着我的教程执行,那你的数据库肯定是没创建的,在部署前需要先手动创建。

ssh 登录服务器,执行以下命令。

检查本地的 config/database.yml,确保 production 块的数据库连接配置在跟服务器上的匹配。

登录服务器,编辑 ~/.profile ,增加环境变量 RAILS_DEPLOYMENT_DEMO_DATABASE_PASSWORD

进入 /var/www/ 目录,创建 rails-deployment-demo 目录并将其权限修改为 deploy 用户。

初始化部署

返回到 rails app 根目录,执行 cap production deploy:initial。如果提示没有读取仓库的权限,则到服务器根据 Generating a new SSH key and adding it to the ssh-agent 创建一对 ssh 密钥,并且把 id_rsa.pub 文件的内容添加到 GitHub 的 ssh keys 设置里。

如无意外的话,控制台应该输出类似以下成功初始化部署的信息。

Last updated

Was this helpful?