在 Vultr VPS 上安装 CentOS9+Rails 7+MySQL8+nginx,并使用 Capistrano3 进行部署
首先
由于 CentOS Stream 9 的发布,我搭建了 Rails 7 开发环境,并进行了现有应用的 Rails、Ruby 版本升级和迁移,因此记录了相关步骤。以下是 CentOS8 文章的 CentOS9 版本。
建议选择Vultr的最便宜的10GB SSD套餐时,如果在CentOS9上使用,可能会出现存储空间不足的问题,建议选择25GB或以上的套餐。
在激安VPS提供商Vultr上,如果您通过我的推荐链接注册账户,可以获得100美元的积分。因此,我尝试了各种组合,如CentOS7、8、MySQL 5.7、8等。由于我不知道这个活动何时结束,所以如果您对此感兴趣,请通过以下链接注册账户。您将获得积分,而且似乎我也会得到一些积分,这是互惠互利的。
通过这个链接您可以获得100美元。
使用的环境
服务器操作系统:CentOS Stream 9
本地操作系统:macOS Monterey版本12.5.1(苹果M1)
Ruby 3.1.2 使用 rbenv
Rails 7.0.3.1
puma 4.3.12
bundler 2.3.21
Capistrano 3.17.1
MySQL 8.0.28
由于在Puma 5中删除了–daemon选项并且重新启动Puma在部署时变得麻烦,所以我故意使用Puma 4。但我打算在有时间的时候进行Puma 5的迁移,因为有解决方案可供选择。(如果你想立即进行迁移,请参考相关文章。)
1. 创建一个Vultr VPS实例
我打算从头开始重新建立,所以创建了一个新的实例。以前东京服务器的价格略高,但现在与NJ的价格相同,所以我选择了东京。
请参考之前的文章《Vultr VPS上CentOS7、Ruby on Rails 6、Puma、Capistrano3部署生产环境的第1-(5)步》来获取Startup Script和SSH Keys的相关信息。
2. 创建登录账户
通过用红色框标注的图标可以访问控制台,使用自动配置的root用户密码进行登录。基本上,因为已连接到互联网,所以在操作系统安装完成后,就会开始试图利用默认安全漏洞进行网络攻击,因此首先要进行安全配置,然后再进行其他操作。
(1) 控制台登录
(2) 可以在稍后使用Capistrano添加帐户。
# adduser deploy
# passwd deploy
# gpasswd -a deploy wheel
# mkdir /home/deploy/.ssh
# chmod 700 /home/deploy/.ssh
# vi /home/deploy/.ssh/authorized_keys
> 公開鍵を貼り付ける(Macで作った/Users/あなた/.ssh/vultr.pubの中身を貼り付けます。)
# chmod 600 /home/deploy/.ssh/authorized_keys
# chown -R deploy:deploy /home/deploy/.ssh/
(3) 确认是否能够通过SSH登录。
只有在第一次输入时会出错,但只要按照以下方式输入”yes”,第二次以后就不会出错了。由于Web控制台未启用HTTPS,密码会以明文形式传输,因此不使用该功能。
$ ssh -i ~/.ssh/vultr2 deploy@1あなたのVPSのIPアドレス
The authenticity of host 'あなたのVPSのIPアドレス (あなたのVPSのIPアドレス)' can't be established.
ED25519 key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxx
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'あなたのVPSのIPアドレス' (ED25519) to the list of known hosts.
Activate the web console with: systemctl enable --now cockpit.socket
[deploy@hogehoge ~]$
2. 操作系统的设置
(1) SSHD的配置
$ sudo vi /etc/ssh/sshd_config
> 以下を変更
PermitRootLogin no # rootのリモートログインを不許可
PasswordAuthentication no # パスワード無しでSSHログイン
ClientAliveInterval 10 # SSHがタイムアウトしないように10秒毎にAlive確認
ClientAliveCountMax 6 # 上記を最大6回(つまり60秒)繰り返す
> 変更を反映
$ sudo systemctl reload sshd
无需密码,从本地计算机进行SSH登录
$ ssh -i ~/.ssh/vultr deploy@あなたのVPSのIPアドレス
确认无法在 root 上进行远程登录。
$ ssh -i ~/.ssh/vultr root@あなたのVPSのIPアドレス
root@あなたのVPSのIPアドレス: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
如果无法正确连接到远程SSH而无法执行操作时,点击“查看控制台”图标,打开控制台并使用root账号登录来恢复连接。
(2) sudo配置
我已经配置使得deploy用户可以无需使用密码执行sudo命令。你可以选择是否进行此设置,不进行设置也是可以的。
(1) 使用visudo命令授予sudo权限。
$ sudo visudo
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
deploy ALL=(ALL) ALL <=この行を追加
## Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL
%deploy ALL=(ALL) NOPASSWD: ALL <=この行を追加
deploy组的用户可以使用sudo命令而无需密码。
[deploy@vultr ~]$ sudo whoami
root
我能使用whoami命令而无需输入密码。
(3) 防火墙的设置
$ sudo yum remove -y firewalld
$ sudo yum install -y iptables-services
$ sudo systemctl start iptables
$ sudo systemctl enable iptables
$ sudo /usr/libexec/iptables/iptables.init save
$ sudo vi /etc/sysconfig/iptables
> Web用に80と433をあける。
# Generated by iptables-save v1.4.21 on Tue Mar 10 01:44:41 2020
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [17:1954]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT <=この行を追加
-A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT <=この行を追加
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Tue Mar 10 01:44:41 2020
> 上記の変更を反映させます。
$ sudo systemctl reload iptables
(4) 交换领域的设定
這次創建的實例只有1GB記憶體,而Rails需要更多記憶體,所以可能會出現記憶體不足的問題,因此我們會設定Swap區域。如果發生頻繁分頁導致性能下降的情況,只需升級Vultr的計劃即可。(請注意,升級後無法降級。)這次我們會保留4GB較大的Swap區域。
由于默认情况下已创建了Swap文件,我们将暂时停止Swap并删除它。
[deploy@vultr ~]$ su
Password:
[root@vultr deploy]# swapoff /swapfile
[root@vultr deploy]# rm /swapfile
rm: remove regular file '/swapfile'? y
创建Swap文件并将其分配给Swap空间。
[root@vultr deploy]# dd if=/dev/zero of=/swapfile bs=1M count=4096
4096+0 records in
4096+0 records out
4294967296 bytes (4.3 GB, 4.0 GiB) copied, 12.6042 s, 341 MB/s
[root@vultr deploy]# mkswap /swapfile
mkswap: /swapfile: insecure permissions 0644, fix with: chmod 0600 /swapfile
Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
no label, UUID=b0a8ad95-0d26-4a3f-933b-911a840d7caf
[root@vultr deploy]# swapon /swapfile
swapon: /swapfile: insecure permissions 0644, 0600 suggested.
[root@vultr deploy]# chmod 0600 /swapfile
[root@vultr deploy]# vi /etc/fstab
> 以下が一番下に無い場合は追加します。
/swapfile swap swap defaults 0 0
> /etc/fstabの変更を保存したら、自動マウントされるか試すためにサーバを再起動する。
[root@vultr deploy]# reboot
重新启动后,使用top命令检查Swap区域。
[deploy@vultr ~]$ top
top - 02:08:14 up 0 min, 1 user, load average: 0.07, 0.03, 0.01
Tasks: 117 total, 1 running, 116 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 956.5 total, 674.2 free, 267.8 used, 157.1 buff/cache
MiB Swap: 4096.0 total, 4096.0 free, 0.0 used. 688.7 avail Mem
3. 安装MySQL8.0
我认为您可以选择使用您喜欢的任何数据库,但是因为据说MySQL 8.0比5.7快两倍,所以我会选择使用8.0版本。
(1) 安装MySQL
如果默认安装了MariaDB,则需要先卸载它,然后再安装MySQL。在东京的Vultr的CentOS 9上并没有预装MariaDB。
[root@vultr deploy]# yum list installed | grep maria
[root@vultr deploy]# yum list installed | grep Maria
[root@vultr deploy]# yum install mysql
Last metadata expiration check: 1:34:06 ago on Mon 05 Sep 2022 01:09:18 AM UTC.
Dependencies resolved.
=======================================================================================================================================================================
Package Architecture Version Repository Size
=======================================================================================================================================================================
Installing:
mysql x86_64 8.0.28-1.el9 appstream 2.6 M
Installing dependencies:
mariadb-connector-c-config noarch 3.2.6-1.el9 appstream 11 k
mysql-common x86_64 8.0.28-1.el9 appstream 75 k
Transaction Summary
=======================================================================================================================================================================
Install 3 Packages
Total download size: 2.7 M
Installed size: 59 M
Is this ok [y/N]: y
Downloading Packages:
(1/3): mariadb-connector-c-config-3.2.6-1.el9.noarch.rpm 466 kB/s | 11 kB 00:00
(2/3): mysql-common-8.0.28-1.el9.x86_64.rpm 1.5 MB/s | 75 kB 00:00
(3/3): mysql-8.0.28-1.el9.x86_64.rpm 13 MB/s | 2.6 MB 00:00
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total 5.0 MB/s | 2.7 MB 00:00
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Preparing : 1/1
Installing : mariadb-connector-c-config-3.2.6-1.el9.noarch 1/3
Installing : mysql-common-8.0.28-1.el9.x86_64 2/3
Installing : mysql-8.0.28-1.el9.x86_64 3/3
Running scriptlet: mysql-8.0.28-1.el9.x86_64 3/3
Verifying : mariadb-connector-c-config-3.2.6-1.el9.noarch 1/3
Verifying : mysql-8.0.28-1.el9.x86_64 2/3
Verifying : mysql-common-8.0.28-1.el9.x86_64 3/3
Installed:
mariadb-connector-c-config-3.2.6-1.el9.noarch mysql-8.0.28-1.el9.x86_64 mysql-common-8.0.28-1.el9.x86_64
Complete!
[root@vultr deploy]# yum install mysql-server
Last metadata expiration check: 1:42:23 ago on Mon 05 Sep 2022 01:09:18 AM UTC.
Dependencies resolved.
=======================================================================================================================================================================
Package Architecture Version Repository Size
=======================================================================================================================================================================
Installing:
mysql-server x86_64 8.0.28-1.el9 appstream 16 M
Installing dependencies:
mecab x86_64 0.996-3.el9.3 appstream 356 k
mysql-errmsg x86_64 8.0.28-1.el9 appstream 473 k
mysql-selinux noarch 1.0.5-1.el9 appstream 36 k
protobuf-lite x86_64 3.14.0-13.el9 appstream 232 k
Transaction Summary
=======================================================================================================================================================================
Install 5 Packages
Total download size: 17 M
Installed size: 116 M
Is this ok [y/N]: y
(2)配置MySQL
[root@vultr deploy]# systemctl start mysqld
[root@vultr deploy]# systemctl enable --now mysqld
Created symlink /etc/systemd/system/multi-user.target.wants/mysqld.service → /usr/lib/systemd/system/mysqld.service.
[root@vultr deploy]# systemctl status mysqld
● mysqld.service - MySQL 8.0 database server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Mon 2022-09-05 02:52:25 UTC; 2min 9s ago
Main PID: 2636 (mysqld)
Status: "Server is operational"
Tasks: 37 (limit: 5877)
Memory: 430.5M
CPU: 5.562s
CGroup: /system.slice/mysqld.service
└─2636 /usr/libexec/mysqld --basedir=/usr
Sep 05 02:52:17 vultr systemd[1]: Starting MySQL 8.0 database server...
Sep 05 02:52:17 vultr mysql-prepare-db-dir[2559]: Initializing MySQL database
Sep 05 02:52:25 vultr systemd[1]: Started MySQL 8.0 database server.
[root@vultr deploy]# mysql_secure_installation
Securing the MySQL server deployment.
Connecting to MySQL using a blank password.
VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?
Press y|Y for Yes, any other key for No: y
There are three levels of password validation policy:
LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 0
Please set the password for root here.
New password:
Re-enter new password:
Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.
Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
- Dropping test database...
Success.
- Removing privileges on test database...
Success.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.
All done!
# vi /etc/my.cnf
> 以下追記
character-set-server = utf8
default_password_lifetime = 0
创建一个用于Rails应用程序的MySQL用户。
创建用于Rails的数据库,并创建数据库用户并授予权限。
# mysql -u root -p
mysql> CREATE DATABASE あなたのアプリ名_production;
mysql> CREATE USER 'DBユーザ名'@'localhost' IDENTIFIED BY 'パスワード';
mysql> GRANT ALL PRIVILEGES ON あなたのアプリ名_production.* TO 'DBユーザ名'@'localhost';
mysql> FLUSH PRIVILEGES;
mysql> exit;
4. 环境建设
安装Ruby、Bundler和其他必要的软件包。
(1)安装 Ruby 3.1.2版本
[root@vultr deploy]# yum groupinstall "Development Tools"
[root@vultr deploy]# yum -y install libyaml-devel
[root@vultr deploy]# yum install -y openssl-devel readline-devel zlib-devel
[root@vultr deploy]# cd /usr/local
[root@vultr deploy]# git clone https://github.com/sstephenson/rbenv.git rbenv
[root@vultr deploy]# git clone https://github.com/sstephenson/ruby-build.git rbenv/plugins/ruby-build
[root@vultr deploy]# vi /etc/profile.d/rbenv.sh
> 以下を記述してパスを通しておく。
export RBENV_ROOT="/usr/local/rbenv"
export PATH="${RBENV_ROOT}/bin:${PATH}"
eval "$(rbenv init --no-rehash -)"
[root@vultr deploy]# source /etc/profile.d/rbenv.sh
[root@vultr deploy]# rbenv install 3.1.2 <=これが時間がかかる。
[root@vultr deploy]# rbenv global 3.1.2
[root@vultr deploy]# rbenv rehash
(2) 安装Bundler 2
[root@vultr local]# gem install bundler
Fetching bundler-2.3.21.gem
Successfully installed bundler-2.3.21
Parsing documentation for bundler-2.3.21
Installing ri documentation for bundler-2.3.21
Done installing documentation for bundler after 0 seconds
1 gem installed
安装 Node.js
[root@vultr local]# yum install -y nodejs
[root@vultr local]# node --version
v16.14.0
安装 yarn
[root@vultr local]# npm install -g yarn
5. 安装Nginx
(1) 通过yum进行安装
[root@vultr local]# yum update
Last metadata expiration check: 2:12:25 ago on Mon 05 Sep 2022 01:09:18 AM UTC.
Dependencies resolved.
Nothing to do.
Complete!
[root@vultr local]# yum info nginx
Last metadata expiration check: 2:12:43 ago on Mon 05 Sep 2022 01:09:18 AM UTC.
Available Packages
Name : nginx
Epoch : 1
Version : 1.20.1
Release : 13.el9
Architecture : x86_64
Size : 39 k
Source : nginx-1.20.1-13.el9.src.rpm
Repository : appstream
Summary : A high performance web server and reverse proxy server
URL : https://nginx.org
License : BSD
Description : Nginx is a web server and a reverse proxy server for HTTP, SMTP, POP3 and
: IMAP protocols, with a strong focus on high concurrency, performance and low
: memory usage.
[root@vultr local]# yum install yum-utils
[root@vultr local]# yum install nginx
(2)在Centos 8上启动Nginx。
[root@vultr local]# systemctl start nginx
[root@vultr local]# systemctl enable nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@vultr local]# systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since Mon 2022-09-05 03:24:17 UTC; 23s ago
Main PID: 24591 (nginx)
Tasks: 2 (limit: 5877)
Memory: 2.0M
CPU: 28ms
CGroup: /system.slice/nginx.service
├─24591 "nginx: master process /usr/sbin/nginx"
└─24592 "nginx: worker process"
Sep 05 03:24:17 vultr systemd[1]: Starting The nginx HTTP and reverse proxy server...
Sep 05 03:24:17 vultr nginx[24589]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Sep 05 03:24:17 vultr nginx[24589]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Sep 05 03:24:17 vultr systemd[1]: Started The nginx HTTP and reverse proxy server.
基本的指令可能因操作系统版本而有些差异,我先写一下。
# systemctl stop nginx
# systemctl restart nginx
# systemctl reload nginx
因为Nginx在默认配置下也可以进行操作验证,所以我们将Vultr VPS的IP地址输入到浏览器中进行确认。
(3) Nginx的配置
構成文件的位置在哪里?
-
- Nginx configuration directory: /etc/nginx
-
- Nginx root directory: /usr/share/nginx/html
- Master/Global configuration file: /etc/nginx/nginx.conf
5. 搭建Rails环境
(1) 为Rails 7做准备工作
# curl https://dl.yarnpkg.com/rpm/yarn.repo > /etc/yum.repos.d/yarn.repo
# dnf --enablerepo=crb -y install ruby-devel rpm-build make gcc gcc-c++ libxml2 libxml2-devel mariadb-devel zlib-devel libxslt-devel nodejs git yarn
# gem install nokogiri -- --use-system-libraries
# gem install webpack
$ npm install -D webpack webpack-cli
$ npm audit fix --force
$ npm install css-loader style-loader -D
$ bundle exec rails webpacker:install
(2) 安装Rails 7.0.3.1
# gem install rails -v 7.0.3.1
...
Done installing documentation for zeitwerk, thor, method_source, concurrent-ruby, tzinfo, i18n, activesupport, nokogiri, crass, loofah, rails-html-sanitizer, rails-dom-testing, rack, rack-test, erubi, builder, actionview, actionpack, railties, mini_mime, marcel, activemodel, activerecord, globalid, activejob, activestorage, actiontext, mail, actionmailer, actionmailbox, websocket-extensions, websocket-driver, nio4r, actioncable, rails after 51 seconds
35 gems installed
# rails -v
Rails 7.0.3.1
(3) 安装mysql2
# gem install mysql2 -- --with-mysql-config=/usr/bin/mysql_config
Building native extensions with: '--with-mysql-config=/usr/bin/mysql_config'
This could take a while...
Successfully installed mysql2-0.5.4
Parsing documentation for mysql2-0.5.4
Installing ri documentation for mysql2-0.5.4
Done installing documentation for mysql2 after 0 seconds
1 gem installed
(2) 测试Rails应用
制作一个适当的应用程序进行动作验证。由于使用Capistrano从本地环境部署,所以只需要适当即可。
(1) 目录准备
$ sudo su
[root@vultrguest var]# mkdir /var/www
[root@vultrguest var]# mkdir /var/www/myapp
[root@vultrguest var]# chown -R deploy.deploy /var/www
(2) Gemfile 准备
$ cd /var/www/myapp
$ source /etc/profile.d/rbenv.sh
$ bundle init
Writing new Gemfile to /var/www/myapp/Gemfile
$ vi Gemfile
# frozen_string_literal: true
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
gem "rails" <= remove "#" here
(3)创建新的 Rails 项目
$ bundle install --path vendor/bundle
$ bundle exec rails new . -B -d mysql --skip-test
exist
create README.md
create Rakefile
create .ruby-version
create config.ru
create .gitignore
create .gitattributes
conflict Gemfile
Overwrite /var/www/myapp/Gemfile? (enter "h" for help) [Ynaqdhm] Y
$ bundle install --path vendor/bundle
$ rails s
=> Booting Puma
=> Rails 7.0.3.1 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.6.5 (ruby 3.1.2-p20) ("Birdie's Version")
* Min threads: 5
* Max threads: 5
* Environment: development
* PID: 31178
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop
6. 用Capistrano3进行部署
我会尝试使用Capistrano3将这个在本地开发环境中创建的应用程序部署到服务器上。
前提条件
- GitHubにSSH公開鍵でローカルからPushできていること。
(1) 准备将应用程序部署至Vultr VPS的目标目录。
$ sudo su
# mkdir /var/www
# mkdir /var/www/myapp
# mkdir /var/www/myapp/shared
# mkdir /var/www/myapp/shared/config
# adduser www
# chown -R www:www /var/www
# chown -R deploy /var/www/myapp
# gpasswd -a deploy www
# gpasswd -a nginx www
(2) 复制指定为非部署目标的文件
$ scp -i ~/.ssh/vultr config/master.key deploy@SERVER_IP_ADDR:/var/www/myapp/shared/config/
$ scp -i ~/.ssh/vultr config/database.yml deploy@SERVER_IP_ADDR:/var/www/myapp/shared/config/
在这里编辑复制的database.yml文件中的production:部分。
production:
<<: *default
database: myapp_production
username: MySQLに作ったアプリ用ユーザー名
password: MySQLに作ったユーザーのパスワード
(3) 与Capistrano相关的配置
# Use Capistrano for deployment
group :development do
gem 'capistrano'
gem 'ed25519'
gem 'bcrypt_pbkdf'
gem 'capistrano-rbenv'
gem 'capistrano-bundler'
gem 'capistrano-rails'
gem 'capistrano3-puma'
end
生成Capfile和config/deploy.rb文件。
$ bundle exec cap install STAGES=production
配置 Capfile 和 config/deploy.rb
# Load DSL and set up stages
require "capistrano/setup"
# Include default deployment tasks
require "capistrano/deploy"
# 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"
require 'capistrano/puma'
install_plugin Capistrano::Puma
install_plugin Capistrano::Puma::Daemon
install_plugin Capistrano::Puma::Nginx
# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }
# config valid for current version and patch releases of Capistrano
lock "~> 3.12.1"
server 'Your Vultr IP ADDR', port: 22, roles: [:app, :web, :db], primary: true
set :application, 'myapp'
set :repo_url, 'git@github.YOU/myapp.git'
set :user, 'deploy'
set :ssh_options, {
forward_agent: true,
user: fetch(:user),
keys: %w(~/.ssh/vultr)
}
# 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"
set :deploy_to, "/var/www/myapp"
# 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"
append :linked_dirs, '.bundle'
append :linked_files, "config/master.key"
append :linked_files, "config/database.yml"
append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets"
# 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
# rbenv
set :rbenv_type, :system
set :rbenv_ruby, File.read('.ruby-version').strip
set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} #{fetch(:rbenv_path)}/bin/rbenv exec"
set :bundle_jobs, 2 <=安いプランなので2。Defaultは4。
# debug log level
set :log_level, :debug <=設定作業中はデバッグモードにした。
(4)Nginx和Puma的事先部署配合
准备VPS的事项
# mkdir /etc/nginx/sites-available
# mkdir /etc/nginx/sites-enabled
# chgrp www sites-available
# chgrp www sites-enabled
使用capistrano-puma插件自动生成配置文件。
使用这些命令在服务器上创建了 /etc/nginx/sites-available 和 shared/puma.rb 两个配置文件。
$ bundle exec cap production puma:nginx_config
00:00 puma:nginx_config
Uploading /tmp/nginx_myapp_production 100.0%
01 sudo mv /tmp/nginx_myapp_production /etc/nginx/sites-available/myapp_production
✔ 01 deploy@Vultr_IP_ADDR 0.200s
02 sudo ln -fs /etc/nginx/sites-available/myapp_production /etc/nginx/sites-enabled/myapp_production
✔ 02 deploy@Vultr_IP_ADDR 0.223s
$ bundle exec cap production puma:config
00:00 puma:config
Uploading /var/www/myapp/shared/puma.rb 100.0%
执行部署
执行部署,确认能正常完成直至puma启动。
$ bundle exec cap production deploy
第一条建议:
如果无法从Vultr服务器加载GitHub,可以尝试使用以下命令将在本地开发环境中使用的SSH密钥添加到GitHub以进行SSH连接。如果在重新创建GitHub存储库时遇到错误,建议尝试此方法。
ssh-add ~/.ssh/id_rsa
提示2:
如果出现OpenSSL错误,请检查是否部署了由config/master.key创建的config/credentials.yml.enc文件。如果~/.bash_profile文件中存在export RAILS_MASTER_KEY=”abc0123456789xyz…”,它将优先于RAILS_MASTER_KEY,如果密钥不匹配,将出现此错误。
第三个提示:
出现Nginx错误:(13:拒绝访问),当尝试通过浏览器访问时出现502错误,通常是因为Nginx的执行用户仍然是默认的nginx用户,并且无法访问/var/www/myapp/shared/tmp/sockets/puma.sock。这种情况下往往是因为Nginx的worker进程的执行用户不是nginx,而是deploy用户。请确认执行用户是否为deploy。
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user deploy; <=ここを確認
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
# Settings for a TLS enabled server.
#
# server {
# listen 443 ssl http2;
# listen [::]:443 ssl http2;
# server_name _;
# root /usr/share/nginx/html;
#
# ssl_certificate "/etc/pki/nginx/server.crt";
# ssl_certificate_key "/etc/pki/nginx/private/server.key";
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 10m;
# ssl_ciphers PROFILE=SYSTEM;
# ssl_prefer_server_ciphers on;
#
# # Load configuration files for the default server block.
# include /etc/nginx/default.d/*.conf;
#
# error_page 404 /404.html;
# location = /40x.html {
# }
#
# error_page 500 502 503 504 /50x.html;
# location = /50x.html {
# }
# }
}
如果所有的权限设置都正确,但仍出现此错误,可能是因为被SELinux限制了。在这种情况下,请尝试以下操作。
$ sudo setenforce Permissive
如果出现了Rails页面,需要进行SELinux策略的更改。
$ sudo grep nginx /var/log/audit/audit.log | audit2allow
$ sudo grep nginx /var/log/audit/audit.log | audit2allow -M nginx
$ sudo semodule -i nginx.pp
$ sudo setenforce Enforcing
建议4:
找不到”webpack”命令。请进行错误处理。
before "deploy:assets:precompile", "deploy:yarn_install"
namespace :deploy do
desc 'Run rake yarn:install'
task :yarn_install do
on roles(:web) do
within release_path do
execute("cd #{release_path} && yarn install")
end
end
end
end
第五个提示:
错误:0308010C:数字信封例程::unsupported错误导致资产预编译失败的原因是Node.js升级到V17并开始使用OpenSSL3。要避免这个问题,可以安装Node Version Manager(NVM)并将Node.js配置为使用LTS版本。
值得注意的是,在我的Vultr环境中,Node.js是V16,但仍然发生了这个错误。不过,按照以下步骤安装了Node.js V16 LTS后,错误得到了解决。
[deploy@vultr ~]$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
登出并使用deploy用户登录以启用NVM,然后执行以下操作。
[deploy@vultr ~]$ nvm install --lts
[deploy@vultr ~]$ nvm use --lts
[deploy@vultr ~]$ node -v
v16.17.0
请参阅上述文章。
在Vultr VPS上安装CentOS 8 + Rails 6 + MySQL 8 + Nginx,并使用Capistrano 3进行部署。
在Vultr VPS上使用CentOS 7,Ruby on Rails 6,Puma,以及Capistrano 3进行生产环境部署。
在CentOS Stream 9上安装Ruby on Rails 7 – Server World。
Nginx错误:(13:权限被拒绝),尝试连接到上游。
命令“webpack”未找到。#522
[已解决] 错误:0308010C:数字信封例程::不支持
使用systemd作为Puma的用户服务启动。