如何使用 Capistrano 自动部署 Rails 上的 Ruby 应用程序

简介


如果您还没有厌倦为使项目上线而重复更新应用服务器的琐碎工作,那么您可能最终会厌倦。当涉及到系统管理的枯燥部分时(如上传代码库、修改配置、反复执行命令等),您在开发项目时所感受到的快乐往往会受到打击。

但不要害怕!任务自动化工具 Capistrano 可以提供帮助。

在这篇DigitalOcean文章中,我们将创建一个坚如磐石的服务器设置,运行最新版本的CentOS,使用Nginx和Passenger托管Ruby-on-Rails应用程序。我们将继续学习如何使用基于 Ruby 的自动化工具 Capistrano 自动完成部署和更新。

注: 本文以 Capistrano 上一篇文章中的知识为基础:使用 Capistrano 自动部署:入门。如果您打算使用该工具,强烈建议您在继续阅读本文之前先阅读这篇文章,以便充分了解该工具。同样,如果你想了解更多有关使用 Passenger(和 Nginx)为基于 Rails 的应用程序部署准备一个新的 droplet 的信息,请查看 How To Deploy Rails Apps Using Passenger With Nginx 一文。

注: Capistrano依赖Git进行部署。要了解更多信息,请点击此处阅读DigitalOcean社区的相关文章。

词汇表


1.准备部署服务器


1.更新和准备操作系统 2.设置 Ruby 环境和 Rails 3.下载并安装应用程序和 HTTP 服务器 4.创建 Nginx 管理脚本 5.配置 Nginx 以部署应用程序 6.下载和安装 Capistrano 7.为部署创建系统用户

2.为基于 Git 的 Capistrano 部署准备 Rails 应用程序


1.创建基本的 Ruby-On-Rails 应用程序 2.创建 Git 仓库

3.使用 Capistrano 实现自动化部署


1.在项目目录内安装 Capistrano 2.在项目目录中使用 config/deploy.rb 3. 3.在项目目录中使用 config/deploy/production.rb 4. 4.部署到生产服务器

准备部署服务器


注: 若要更好地理解以下部分(可视为冗长的摘要),请查看有关该主题的完整文章:如何使用 Passenger 和 Nginx 部署 Rails 应用程序

更新和准备操作系统


运行以下命令,更新基于 CentOS 的软件包的默认工具:

1yum -y update

执行以下命令,安装包含开发工具的软件包:

1yum groupinstall -y 'development tools'

本教程所需的某些软件包(如 libyaml-devel、nginx 等)在 CentOS 官方软件仓库中找不到。

运行以下命令添加 EPEL 资源库:

1sudo su -c 'rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm'
2
3yum -y update

最后,为了安装一些额外的库和工具,请运行以下命令:

1yum install -y curl-devel nano sqlite-devel libyaml-devel

设置 Ruby 环境和 Rails


注: 本节是我们的专门文章如何在 CentOS 6.5 上安装 Ruby 2.1.0的摘要。

运行以下两条命令安装 RVM 并为 Ruby 创建系统环境:

1curl -L get.rvm.io | bash -s stable
2
3source /etc/profile.d/rvm.sh
4rvm reload
5rvm install 2.1.0

由于 Rails 需要 JavaScript 解释器,我们还需要设置 Node.js。

运行以下命令,使用 yum 下载并安装 nodejs:

1yum install -y nodejs

使用 RubyGems 的 gem 执行以下命令,下载并安装 rails

1gem install bundler rails

下载和安装应用程序及 HTTP 服务器


注: 如果您的VPS内存不足1GB,您需要执行以下简单步骤,准备一个SWAP磁盘空间作为临时数据存储空间(内存替代)。由于DigitalOcean服务器配备了快速固态硬盘,因此在执行服务器应用程序安装任务时,这并不构成真正的问题。

1# Create a 1024 MB SWAP space
2sudo dd if=/dev/zero of=/swap bs=1M count=1024
3sudo mkswap /swap
4sudo swapon /swap

Phusion Passenger


Red Hat Linux 的默认软件包管理器 RPM(RPM 软件包管理器)将应用程序包含在.rpm文件中。不幸的是,就 Passenger 而言,这些文件已经过时。因此,我们将再次使用 RubyGem 下载并安装 Passenger 的最新可用版本 -- ** 版本 4** 。

使用下面的命令下载并安装 passenger:

1gem install passenger

Nginx


注意: 通常情况下,要下载并安装 Nginx,您可以添加 EPEL 资源库(就像我们已经做的),并通过 yum 获取 Nginx。然而,要让 Nginx 与 Passenger 配合使用,其源代码必须与必要的模块一起编译。

运行以下命令,开始使用本地 Passenger 模块编译 Nginx:

1passenger-install-nginx-module

运行命令后,按 Enter 键并确认语言选择(在我们的例子中就是 Ruby)。如果你愿意,可以使用方向键和空格键单独选择 Ruby。

1Use <space> to select.
2If the menu doesn't display correctly, ensure that your terminal supports UTF-8.
3
4 ‣ ⬢  Ruby
5   ⬢  Python
6   ⬢  Node.js
7   ⬡  Meteor

下一步,选择 "项目 1":

11. Yes: download, compile and install Nginx for me. (recommended)
2    The easiest way to get started. A stock Nginx 1.4.4 with Passenger
3    support, but with no other additional third party modules, will be
4    installed for you to a directory of your choice.

然后按回车键继续。

现在,Nginx 源代码将被下载、编译和安装,并支持 Passenger。

注: 这项工作可能需要一些时间,可能比人们希望或预期的时间要长!

创建 Nginx 管理脚本


编译完 Nginx 后,为了轻松控制它,我们需要创建一个简单的管理脚本。

运行以下命令创建脚本:

1nano /etc/rc.d/init.d/nginx

复制并粘贴以下内容:

 1#!/bin/sh
 2. /etc/rc.d/init.d/functions
 3. /etc/sysconfig/network
 4[ "$NETWORKING" = "no" ] && exit 0
 5
 6nginx="/opt/nginx/sbin/nginx"
 7prog=$(basename $nginx)
 8
 9NGINX_CONF_FILE="/opt/nginx/conf/nginx.conf"
10
11lockfile=/var/lock/subsys/nginx
12
13start() {
14    [ -x $nginx ] || exit 5
15    [ -f $NGINX_CONF_FILE ] || exit 6
16    echo -n $"Starting $prog: "
17    daemon $nginx -c $NGINX_CONF_FILE
18    retval=$?
19    echo
20    [ $retval -eq 0 ] && touch $lockfile
21    return $retval
22}
23
24stop() {
25    echo -n $"Stopping $prog: "
26    killproc $prog -QUIT
27    retval=$?
28    echo
29    [ $retval -eq 0 ] && rm -f $lockfile
30    return $retval
31}
32
33restart() {
34    configtest || return $?
35    stop
36    start
37}
38
39reload() {
40    configtest || return $?
41    echo -n $”Reloading $prog: ”
42    killproc $nginx -HUP
43    RETVAL=$?
44    echo
45}
46
47force_reload() {
48    restart
49}
50
51configtest() {
52    $nginx -t -c $NGINX_CONF_FILE
53}
54
55rh_status() {
56    status $prog
57}
58
59rh_status_q() {
60    rh_status >/dev/null 2>&1
61}
62
63case "$1" in
64start)
65rh_status_q && exit 0
66$1
67;;
68stop)
69rh_status_q || exit 0
70$1
71;;
72restart|configtest)
73$1
74;;
75reload)
76rh_status_q || exit 7
77$1
78;;
79force-reload)
80force_reload
81;;
82status)
83rh_status
84;;
85condrestart|try-restart)
86rh_status_q || exit 0
87;;
88*)
89echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
90exit 2
91esac

按 CTRL+X 并用 Y 确认保存并退出。

将此管理脚本的模式设置为可执行:

1chmod +x /etc/rc.d/init.d/nginx

配置 Nginx 以部署应用程序


在配置服务器的最后一步,我们需要创建一个 Nginx 服务器块,大致相当于 Apache 的虚拟主机。

你可能还记得在 Passenger 的 Nginx 安装过程中看到的,这个过程包括在 Nginx 的配置文件 nginx.conf 中添加代码块。默认情况下,除非另有说明,该文件位于 /opt/nginx/conf/nginx.conf

键入以下命令打开配置文件,使用文本编辑器 nano 进行编辑:

1nano /opt/nginx/conf/nginx.conf

第一步,找到 "http {"节点,并在 "passenger_root "和 "passenger_ruby "指令后添加以下内容:

1# Only for development purposes.
2# Remove this line when you upload an actual application.
3# For * TESTING * purposes only.
4passenger_app_env development;

向下滚动文件,找到 server { ...。注释掉默认位置,即

1..
2
3#    location / {
4#            root html;
5#            index index.html index.htm;
6#        }
7
8..

并定义默认应用程序根目录:

1# Set the folder where you will be deploying your application.
2# We are using: /home/deployer/apps/my_app
3root              /home/deployer/apps/my_app/public;
4passenger_enabled on;

按 CTRL+X 并用 Y 确认保存并退出。

运行以下命令,用新的应用程序配置重新加载 Nginx:

1# !! Remember to create an Nginx management script
2#    by following the main Rails deployment article for CentOS
3#    linked at the beginning of this section.
4
5/etc/init.d/nginx restart

要检查 Nginx 的状态,可以使用

1/etc/init.d/nginx status

注: 要了解有关 Nginx 的更多信息,请参阅 如何在 VPS 上配置 Nginx Web 服务器

下载和安装 Capistrano


系统准备就绪后,我们就可以借助 RubyGems 轻松获取 Capistrano 的最新版本了。

您只需使用以下命令即可获得 Capistrano 3 版本:

1gem install capistrano

为部署创建系统用户


在这一步中,我们将创建一个 CentOS 系统用户来执行部署操作。这将是 Capistrano 使用的用户。

注: 为保持基本功能,我们将创建一个具有必要权限的 "deployer "用户。如需更完整的设置,请考虑使用 Capistrano 入门教程中的 groups 示例。

创建新的系统用户 deployer

1adduser deployer

设置 deployer 的密码:

1passwd deployer
2
3# Enter a password
4# Confirm the password

使用文本编辑器 nano 编辑 /etc/sudoers

1nano /etc/sudoers

向下滚动文件,找到定义 root 的位置:

1..
2
3## The COMMANDS section may have other options added to it.
4##
5## Allow root to run any commands anywhere
6root ALL=(ALL)	ALL
7
8..

root ALL=(ALL) ALL 后面添加以下内容:

1deployer ALL=(ALL) ALL

现在,/etc/sudoers文件的这一部分应该是这样的:

1..
2
3## The COMMANDS section may have other options added to it.
4##
5## Allow root to run any commands anywhere
6root ALL=(ALL)	ALL
7deployer ALL=(ALL) ALL
8
9..

按 CTRL+X 并用 Y 确认保存并退出。

为基于 Git 的 Capistrano 部署准备 Rails 应用程序


一旦我们的系统准备就绪,所有必要的应用程序都已设置并正常运行,我们就可以着手创建一个示例性的 Rails 应用程序作为样本。

在第二阶段,我们将创建一个 Git 仓库,并将代码库推送到 Github 上可访问的中心位置,以便 Capistrano 用于部署。

注意: 这里我们创建的是一个示例应用程序。对于实际部署,您应在确保所有内容都已备份后自行执行这些操作--以防万一!_ 另外,请注意,您需要在与需要部署应用程序的服务器不同的位置运行 Capistrano。

创建基本的 Ruby-On-Rails 应用程序


注: 下面的步骤是创建一个替代的 Rails 应用程序来试用 Capistrano。

安装好 Ruby 和 Rails 后,我们只需执行一条命令即可开始工作。

执行以下命令,让 Rails 创建一个名为 my_app 的新应用程序:

 1# Create a sample Rails application
 2rails new my_app
 3
 4# Enter the application directory
 5cd my_app
 6
 7# Create a sample resource
 8rails generate scaffold Task title:string note:text
 9
10# Create a sample database
11RAILS_ENV=development rake db:migrate

要测试应用程序的设置是否正确以及一切运行是否正常,请进入应用程序目录并通过 rails s 运行一个简单的服务器:

 1# Enter the application directory
 2cd my_app
 3
 4# Run a simple server
 5rails s
 6
 7# You should now be able to access it by
 8# visiting: http://[your droplet's IP]:3000
 9
10# In order to terminate the server process,
11# Press CTRL+C

创建 Git 仓库


注: 若想了解更多关于Git的使用方法,请查看DigitalOcean社区页面上的如何有效使用Git教程。

注: 要学习本节内容,你需要一个 Github 账户。或者,你也可以根据this DigitalOcean 的相关文章设置一个 droplet 来托管自己的 Git 仓库。如果您选择这样做,请确保在部署文件中使用相关 URL。

我们将使用 Github提供的示例说明来创建源代码库。

在 "my_app "目录下执行以下不言自明的命令来启动版本库:

 1# !! These commands are to be executed on
 2#    your development machine, from where you will
 3#    deploy to your server.
 4#    Instructions might vary slightly depending on
 5#    your choice of operating system.
 6#
 7#    Make sure to set correct paths for application
 8#    Otherwise Nginx might not be able to locate it.
 9
10# Initiate the repository
11git init
12
13# Add all the files to the repository
14git add .
15
16# Commit the changes
17git commit -m "first commit"
18
19# Add your Github repository link 
20# Example: git remote add origin [email protected]:[user name]/[proj. name].git
21git remote add origin git@github.com:user123/my_app.git
22
23# Create an RSA/SSH key
24# Follow the on-screen instructions
25ssh-keygen -t rsa
26
27# View the contents of the key and add it to your Github
28# by copy-and-pasting from the current remote session by
29# visiting: https://github.com/settings/ssh
30# To learn more about the process,
31# visit: https://help.github.com/articles/generating-ssh-keys
32cat /root/.ssh/id_rsa.pub
33
34# Set your Github information
35# Username:
36# Usage: git config --global user.name "[your username]"
37git config --global user.name "user123"
38
39# Email:
40# Usage: git config --global user.email "[your email]"
41git config --global user.email "[email protected]"
42
43# Push the project's source code to your Github account
44git push -u origin master

使用 Capistrano 自动进行部署


正如我们在第一篇 Capistrano 文章中提到的,开始使用该库的方法是将其安装到项目目录中。在本节中,我们将了解如何安装,然后创建设置服务器所需的文件。

在项目目录内安装 Capistrano


我们文章中的另一个简单步骤是安装 Capistrano 文件。下面的命令将构建一些目录和文件,供部署工具使用。

运行以下程序启动(即_install_)Capistrano 文件:

1cap install
2
3# mkdir -p config/deploy
4# create config/deploy.rb
5# create config/deploy/staging.rb
6# create config/deploy/production.rb
7# mkdir -p lib/capistrano/tasks
8# Capified

在项目目录内使用 config/deploy.rb


文件 deploy.rb 包含与部署服务器相关的参数和设置。在这里,我们将告诉 Capistrano 我们要连接和部署哪个(些)服务器,以及如何连接和部署。

注意: 编辑文件(或定义配置)时,可以注释或添加新行。请确保不要** *一些示例设置覆盖您添加的设置。

运行以下程序,使用 nano 文本编辑器编辑文件:

1nano config/deploy.rb

添加以下代码块,并根据自己的设置进行修改:

 1# Define the name of the application
 2set :application, 'my_app'
 3
 4# Define where can Capistrano access the source repository
 5# set :repo_url, 'https://github.com/[user name]/[application name].git'
 6set :scm, :git
 7set :repo_url, 'https://github.com/user123/my_app.git'
 8
 9# Define where to put your application code
10set :deploy_to, "/home/deployer/apps/my_app"
11
12set :pty, true
13
14set :format, :pretty
15
16# Set the post-deployment instructions here.
17# Once the deployment is complete, Capistrano
18# will begin performing them as described.
19# To learn more about creating tasks,
20# check out:
21# http://capistranorb.com/
22
23# namespace: deploy do
24
25#   desc 'Restart application'
26#   task :restart do
27#     on roles(:app), in: :sequence, wait: 5 do
28#       # Your restart mechanism here, for example:
29#       execute :touch, release_path.join('tmp/restart.txt')
30#     end
31#   end
32
33#   after :publishing, :restart
34
35#   after :restart, :clear_cache do
36#     on roles(:web), in: :groups, limit: 3, wait: 10 do
37#       # Here we can do anything such as:
38#       # within release_path do
39#       #   execute :rake, 'cache:clear'
40#       # end
41#     end
42#   end
43
44# end

按 CTRL+X 并用 Y 确认保存并退出。

在项目目录内使用 config/deploy/production.rb


注意:deploy.rb 类似,您需要对 production.rb 文件进行一些修改。最好是修改代码,而不是添加下面的代码块。

运行以下程序,使用 nano 文本编辑器编辑文件:

1nano config/deploy/production.rb

输入服务器设置,如下所示:

 1# Define roles, user and IP address of deployment server
 2# role :name, %{[user]@[IP adde.]}
 3role :app, %w{[email protected]}
 4role :web, %w{[email protected]}
 5role :db,  %w{[email protected]}
 6
 7# Define server(s)
 8server '162.243.74.190', user: 'deployer', roles: %w{web}
 9
10# SSH Options
11# See the example commented out section in the file
12# for more options.
13set :ssh_options, {
14    forward_agent: false,
15    auth_methods: %w(password),
16    password: 'user_deployers_password',
17    user: 'deployer',
18}

按 CTRL+X 并用 Y 确认保存并退出。

部署到生产服务器


完成设置后,就可以进行部署了。

在开发机器上运行以下代码,将其部署到生产服务器上。根据上述文件的定义,Capistrano 将

  • 连接部署服务器
  • 下载应用程序源代码
  • 执行部署操作(即获取乘客信息,重启应用程序)
1cap production deploy

要了解有关 Capistrano 及其功能的更多信息,请阅读 Capistrano 文档

Submitted by: O.S. Tezer
Published At
Categories with 技术
comments powered by Disqus