Ubuntu16.04下使用Capistrano+Nginx+Puma部署Rails 5.2

首先得有一台云服务器。

1.云服务器用户配置

首先,在云服务器上创建用户,用root登录后,创建deploy用户

adduser deploy

新增 /etc/sudoers.d/deploy,添加如下内容, 让新用户可以使用sudo:

deploy ALL=(ALL:ALL) ALL

切换到deploy用户,给deploy设置免密码登录,在当前目录下执行:

mkdir ~/.ssh
touch ~/.ssh/authorized_keys

回到本地电脑,把公钥复制出来,执行:

cat ~/ssh/id_rsa.pub

回到服务器,把刚复制的公钥放进去,执行:

vi ~/.ssh/authorized_keys

修改权限:

chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys

退出后,重新登录,会发现不需要输入密码 了。

2.更新和安装Liunx套件

先更新系统, 再升级。终端执行:

sudo apt-get update -y
sudo apt-get upgrade -y

3.安装Ruby on Rails 所需要的东西

sudo apt-get install -y build-essential git-core bison openssl libreadline6-dev curl zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 autoconf libc6-dev libpcre3-dev libcurl4-nss-dev libxml2-dev libxslt-dev imagemagick nodejs libffi-dev

4.安装Ruby,Rails

安装 RVM:

sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
curl -sSL https://get.rvm.io | bash -s stable
source ~/.rvm/scripts/rvm
rvm requirements

安装ruby,这里选2.4.0:

rvm install 2.4.0
rvm use 2.4.0 --default

安装rails

gem install rails

安装bundler:

gem install bundler --no-ri --no-rdoc

安装5.PostgreSQL

首先,更新apt-get:

sudo apt-get update

然后安装PostgreSQL及其开发库:

sudo apt-get install postgresql postgresql-contrib libpq-dev

PostgreSQL现在已经安装,但你应该创建一个新的数据库用户,你的Rails应用程序将使用。
使用此命令创建一个PostgreSQL超级用户用户(pguser换成你需要的用户名):

sudo -u postgres createuser -s pguser

如果要为数据库用户设置密码,请使用以下命令输入PostgreSQL控制台:

sudo -u postgres psql

PostgreSQL的控制台被显示postgres=#提示符。 在PostgreSQL提示符处,输入此命令以设置您创建的数据库用户的密码:

\password pguser

在提示符处输入所需的密码,然后进行确认。

现在您可以通过输入以下命令退出PostgreSQL控制台:

\q

因为rails连接数据库的时候,可能会失败。修改 /etc/postgresql/9.5/main/pg_hba.conf

sudo vim /etc/postgresql/9.5/main/pg_hba.conf
图片.png

修改保存,重新启动pg

sudo service postgresql restart

6.安装Nignx

sudo apt-get install nginx
sudo service nginx start

7.安装Capistrano

在本地的rails项目中gemfile中加入

group :development do
  gem 'capistrano', '3.11.0'
  gem 'capistrano-rvm', '0.1.2'
  gem 'capistrano-rails', '1.4.0'
  gem 'capistrano3-puma', '3.1.1'
  gem 'capistrano-bundler'
  gem 'sshkit-sudo' #cap staging puma:nginx_config 出现错误
end

然后执行

bundle install

创建 capfile

bundle exec cap install

配置Capfile:

# Load DSL and set up stages
require "capistrano/setup"

# Include default deployment tasks
require "capistrano/deploy"

# 添加
require "capistrano/rvm"
require 'capistrano/rails'
require 'capistrano/puma'
require 'capistrano/puma/nginx'
require 'sshkit/sudo'
require 'capistrano/bundler'
install_plugin Capistrano::Puma
install_plugin Capistrano::Puma::Nginx

# Load the SCM plugin appropriate to your project:
#
# require "capistrano/scm/hg"
# install_plugin Capistrano::SCM::Hg
# or
# require "capistrano/scm/svn"
# install_plugin Capistrano::SCM::Svn
# or
require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git

# Include tasks from other gems included in your Gemfile
#
# For documentation on these, see for example:
#
#   https://github.com/capistrano/rvm
#   https://github.com/capistrano/rbenv
#   https://github.com/capistrano/chruby
#   https://github.com/capistrano/bundler
#   https://github.com/capistrano/rails
#   https://github.com/capistrano/passenger
#
# require "capistrano/rvm"
# require "capistrano/rbenv"
# require "capistrano/chruby"
# require "capistrano/bundler"
# require "capistrano/rails/assets"
# require "capistrano/rails/migrations"
# require "capistrano/passenger"

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }


配置config/deploy.rb:

# config valid for current version and patch releases of Capistrano
lock "~> 3.11.0"

set :application, "hpd_demos"  ## demo 换成你的项目名
set :repo_url, "https://github.com/602041937/rails_demos.git" ## 这里写上项目代码的托管地址
append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets", "public/system", "public/uploads", "vendor/bundle",".bundle"
append :linked_files, "config/database.yml", "config/master.key"

set :rvm_type, :user
set :rvm_ruby_version, '2.4.0'

# 需要运行命令创建这3个文件夹
namespace :deploy do
  namespace :check do
    desc 'Create Directories for Pid, Log and Socket'
    task :make_pid_log_and_socket_dirs do
      on roles(:all) do
        execute "mkdir -p #{shared_path}/tmp/sockets"
        execute "mkdir -p #{shared_path}/tmp/pids"
        execute "mkdir -p #{shared_path}/log"
      end
    end
  end
end



# Default branch is :master
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp

# Default deploy_to directory is /var/www/my_app_name
# set :deploy_to, "/var/www/my_app_name"

# Default value for :format is :airbrussh.
# set :format, :airbrussh

# You can configure the Airbrussh format using :format_options.
# These are the defaults.
# set :format_options, command_output: true, log_file: "log/capistrano.log", color: :auto, truncate: :auto

# Default value for :pty is false
# set :pty, true

# Default value for :linked_files is []
# append :linked_files, "config/database.yml"

# Default value for linked_dirs is []
# append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets", "public/system"

# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }

# Default value for local_user is ENV['USER']
# set :local_user, -> { `git config user.name`.chomp }

# Default value for keep_releases is 5
# set :keep_releases, 5

# Uncomment the following to require manually verifying the host key before first deploy.
# set :ssh_options, verify_host_key: :secure


配置 config/deploy/staging.rb:

# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:

# server "example.com", user: "deploy", roles: %w{app db web}, my_property: :my_value
# server "example.com", user: "deploy", roles: %w{app web}, other_property: :other_value
# server "db.example.com", user: "deploy", roles: %w{db}


# role-based syntax
# ==================

# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.

# role :app, %w{deploy@example.com}, my_property: :my_value
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db,  %w{deploy@example.com}


# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.


# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult the Net::SSH documentation.
# http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start
#
# Global options
# --------------
#  set :ssh_options, {
#    keys: %w(/home/rlisowski/.ssh/id_rsa),
#    forward_agent: false,
#    auth_methods: %w(password)
#  }
#
# The server-based syntax can be used to override options:
# ------------------------------------
# server "example.com",
#   user: "user_name",
#   roles: %w{web app},
#   ssh_options: {
#     user: "user_name", # overrides user setting above
#     keys: %w(/home/user_name/.ssh/id_rsa),
#     forward_agent: false,
#     auth_methods: %w(publickey password)
#     # password: "please use keys"
#   }

server '106.12.127.211', user: 'deploy', roles: %w{app db web}
set :deploy_to, "/home/deploy/hpd_demos/#{fetch(:rails_env)}"
set :branch, :capistrano2
set :stage, :staging
set :ssh_options, {
    keys: %w(/home/deploy/.ssh/authorized_keys),
    auth_methods: %w(publickey)
}

8.运行capistrano的相关命令

依次运行一下命令,如果发生错误,看错误提示,一般都能解决问题

cap staging deploy:check
cap staging puma:config
cap staging puma:nginx_config
cap staging deploy

8.1 cap staging deploy:check可能遇到的问题

在本地运行命令

cap staging deploy:check

可能会提示你database.yml,master.key 不存在。

在远端服务器上创建/home/deploy/hpd_demos/shared/config/database.yml:

staging:
  adapter: postgresql
  database: rails_demos_staging
  username: hpd
  password: 123456789
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000
  encoding: utf8

创建 /home/deploy/demo/shared/config/master.key , 把本机的master key贴进去,这里master.key取代了之前的secrets。
修改hpd_demos目录下所有文件的权限:

cd /home/deploy/hpd_demos
chown -R deploy:deploy .

其中,第一个deploy是指用户名,第二个deploy是指group 名,deploy默认属于deploy组。

8.2 cap staging deploy可能遇到的问题

  1. 可能会出现 database "rails_demos_staging" does not exist
    解决:到服务器的项目releases下选择最新配置项目下,运行
RAILS_ENV=staging rails db:create

9.重启nginx

sudo service nginx restart

参考链接:https://luciaca.cn/2018/07/08/deploy-with-capistrano-nginx-and-puma-on-rails/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341