【山竹记账后端】16.部署应用和文档


大纲链接 §

[toc]


1. 前提条件与依赖升级 ⇧

前提条件 ⇧


由于开发过程中新增依赖,和部分依赖被发现有安全风险,导致运行脚本,服务器安装时产生错误,需要升级 Ruby 版本

Ruby 升级到 3.2.11(本地版本和 Docker 基础镜像都升级) ⇧

  • 重新测试打包到远程服务器的脚本,报错说 nokogiri@1.18.10 无法获取依赖
    • 查看包nokogiri是由于此版本有安全漏洞,无法在服务器上拉取依赖,最新版必须依赖于 Ruby@3.2+
  • 环境与依赖:Ruby 从 3.1.2 升级到 3.2.11(本地版本和 Docker 基础镜像都升级)
  • Bundler 固定为 2.4.19
  • nokogiri 显式声明并升级到 1.19.7;
  • RubyGems 镜像源在清华和中科大之间来回切换,依赖声明里最终用的是中科大源

修改 config/host.Dockerfile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
FROM ruby:3.2.11

ENV RAILS_ENV=production

# 切换源
RUN bundle config mirror.https://rubygems.org "https://mirrors.ustc.edu.cn/rubygems/"
# RUN bundle config mirror.https://rubygems.org https://mirrors.tuna.tsinghua.edu.cn/rubygems
# RUN bundle config mirror.https://rubygems.org https://docker.1ms.run/rubygems

# 安装打包器依赖
RUN gem install bundler:2.4.19
RUN gem --version
RUN bundle --version

# 新建工作空间
RUN mkdir /mangosteen
WORKDIR /mangosteen

ADD Gemfile /mangosteen
ADD Gemfile.lock /mangosteen
ADD vendor/cache.tar.gz /mangosteen/vendor/
ADD vendor/rspec_api_documentation.tar.gz /mangosteen/vendor/
RUN bundle config set --local without 'development test'
RUN bundle install --local

ADD mangosteen-*.tar.gz ./
ENTRYPOINT ["bundle", "exec", "puma"]

修改 .ruby-version

  • echo "3.2.11" > .ruby-version

    1
    
    ruby-3.2.11

本地使用 rvm 更新 ruby

  • 旧版 RVM 的版本列表可能不包含较新的 Ruby 补丁版本,先更新 RVM 并重载配置

    1
    2
    
    rvm get stable
    rvm reload

安装目标 Ruby 版本

1
rvm install 3.2.11

切换默认版本并更新项目配置

1
2
rvm use 3.2.11 --default
ruby -v

重装依赖并清理缓存

  • RVM 会为每个 Ruby 版本创建独立的 Gem 环境,切换后需要重新安装 Bundler 和项目依赖,并清理旧版本残留的缓存

    1
    2
    3
    
    gem install bundler
    bundle install
    rm -rf tmp/cache
  • 运行 bundle install 与 bundle update

  • 回归测试 rspec 通过

  • 文档生成 bin/rake docs:generate 通过

参考


AutoJwt 中间件重构 ⇧

镜像启动失败,自动退出,镜像打包过程中报错,查看日志 docker logs mangosteen-prod-1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
docker logs mangosteen-prod-1
Puma starting in single mode...
* Puma version: 8.0.2 ("Into the Arena")
* Ruby version: ruby 3.2.11 (2026-03-27 revision 5483bfc1ae) [x86_64-linux]
* Min threads: 3
* Max threads: 3
* Environment: production
* PID: 1
! Unable to load application: NameError: uninitialized constant Middleware::AutoJwt
bundler: failed to load command: puma
...
  • 提示 uninitialized constant Middleware::AutoJwt 错误
  • 核心原因在于 Rails 生产环境的 Zeitwerk 自动加载机制报错
  • 在本地开发环境中(development),Rails 默认按需加载代码;
  • 但在生产环境(production)启动时,Rails 会执行 eager_load(预加载所有文件)
    • 严格检查文件路径与类/模块命名是否完全一致。
  • 项目中的 lib/middleware/auto_jwt.rb,Zeitwerk 根据文件路径推断它应该定义 Middleware::AutoJwt
    • 但文件里的实际写法不符合规范,缺少外层 Middleware 命名空间,并且驼峰命名类名一致 AutoJwt
  • 本地模拟生产环境验证(推荐)命令: RAILS_ENV=production bundle exec rails zeitwerk:check
    • 在重新打包 Docker 镜像前,可以在本地终端运行以下命令测试预加载是否通过,避免反复打包耗时
    • 输出 Hold on, I am eager loading the application. All is good!,说明加载问题已彻底解决

修改 lib/middleware/auto_jwt.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
require "set"

module Middleware
  class AutoJwt
    # 初始化中间件.
    # @param [Object] app Param documentation.
    # @return [Object]
    def initialize(app)
      @app = app
    end
    # 从请求头中获取 jwt,并解析.
    # @param [Object] env Param documentation.
    # @raise [StandardError]
    # @raise [JWT::ExpiredSignature]
    # @return [Array]
    def call(env)
      # ...
      @status, @headers, @response = @app.call(env)
      [ @status, @headers, @response ]
    end
  end
end
  • 确保它的命名空间类名和路径严格对应

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    # 文件路径:app/middleware/auto_jwt.rb 或 lib/middleware/auto_jwt.rb
    module Middleware
    class AutoJwt
    def initialize(app)
      @app = app
    end
    
    def call(env)
      # 你的中间件逻辑...
      @app.call(env)
    end
    end
    end

config/application.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
require_relative "boot"

require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_mailbox/engine"
require "action_text/engine"
require "action_view/railtie"
require "action_cable/engine"
require_relative "../lib/middleware/auto_jwt"

Bundler.require(*Rails.groups)

module Mangosteen1
  class Application < Rails::Application
    config.load_defaults 7.2
    config.autoload_lib(ignore: %w[assets tasks])
    config.api_only = true
    # 挂载中间件
    config.middleware.use Middleware::AutoJwt
  end
end
  • 配置了 config.autoload_lib(ignore: %w[assets tasks]),它会自动加载 lib/ 下的所有子目录并映射为命名空间
  • 相对路径引用 require_relative "../lib/middleware/auto_jwt"
  • 挂载中间件 config.middleware.use Middleware::AutoJwt

再次运行 RAILS_ENV=production bin/bundle exec rails zeitwerk:check 通过检查 All is good!


其他需要注意的 ⇧

  • 尝试如果拉镜像失败,注意检查是否开启系统的 proxy,挂梯子有时候需要关闭/开启梯子,尝试是否拉取成功
  • 修改 /etc/docker/daemon.json 配置镜像后,需要重启 docker
    • systemctl daemon-reload
    • systemctl restart docker

远程服务器重装了系统、更换了 SSH 服务配置或 IP 被重新分配,导致本地保存的指纹与服务器当前指纹不一致

  • 使用 ssh root@xxx.xxx.xxx.xx 登录远程服务器报错

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    @    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
    Someone could be eavesdropping on you right now (man-in-the-middle attack)!
    It is also possible that a host key has just been changed.
    The fingerprint for the ED25519 key sent by the remote host is
    SHA256:zwBl1MtSi3SAoTyc449+c9f8+xhdLitDCOUs9vdPZxk.
    Please contact your system administrator.
    Add correct host key in /c/Users/JoelXu/.ssh/known_hosts to get rid of this message.
    Offending ECDSA key in /c/Users/JoelXu/.ssh/known_hosts:8
    Host key for xxx.xxx.xx.xxx has changed and you have requested strict checking.
    Host key verification failed.
  • 清理旧指纹:在终端中运行以下命令,删除 known_hosts 文件中关于该 IP 的旧记录

    1
    2
    
    ssh-keygen -R xxx.xxx.xxx.xx
    ssh-keygen -R server1
  • 重新连接服务器: 清理完成后,再次执行登录命令 ssh root@xxx.xxx.xxx.xx

  • 确认新指纹:

    • 系统会提示 Are you sure you want to continue connecting (yes/no/[fingerprint])?
    • 直接输入 yes 并回车,系统会自动将新的服务器密钥写入本地文件并完成登录

注意本地/远程生产环境服务器启动 puma 默认使用 https ⇧

测试本地生产环境,可临时设置 config/environments/production.rb 使用 http

  • 临时设置 config.force_ssl = false
  • 设置完成后重新运行 bin/pack_for_host.sh
  • 测试完成别忘记需要重新设置回 config.force_ssl = true
  • 可用来测试的 curl 命令
    • curl --noproxy "*" -v http://localhost:3000
    • curl --noproxy "*" -v --data "email=xxx@163.com" http://localhost/api/v1/validation_codes

部署流程:源码打包时不再包含依赖目录,依赖缓存单独压缩上传,上传后自动删除本地压缩包;部署脚本还增加了步骤标题、交互式设置环境变量(写入 ~/.bashrc)、创建数据库容器,以及是否更新数据库的确认

2. 部署服务器 ⇧

修改本地打包、本地初始化脚本 ⇧

bin/pack_for_host.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/bin/bash

# pack_for_host.sh

# 检查目标目录并动态设置基础路径
if [ -d "/IdeaProjects" ]; then
  BASE_DIR="/IdeaProjects"
elif [ -d "/workspaces" ]; then
  BASE_DIR="/workspaces"
else
  echo "错误: 未找到 /workspaces 或 /IdeaProjects 目录,脚本退出。"
  exit 1
fi
echo "检测到有效目录,使用基础路径: ${BASE_DIR}"

# 注意修改 oh-my-env2 目录名为你的项目根目录名称,已持久化映射到工作镜像环境工作空间
dir=oh-my-env-2
# 日期时间格式作为版本号
time=$(date +'%Y%m%d-%H%M%S')
# 压缩包文件名称
dist=tmp/mangosteen-$time.tar.gz
current_dir=$(dirname $0)
deploy_dir=$BASE_DIR/$dir/mangosteen_deploy
gemfile=$current_dir/../Gemfile
gemfile_lock=$current_dir/../Gemfile.lock
vendor_dir=$current_dir/../vendor
vendor_1=rspec_api_documentation

function title {
  echo
  echo "###############################################################################"
  echo "## $1"
  echo "###############################################################################"
  echo
}

yes | rm tmp/mangosteen-*.tar.gz;
yes | rm $deploy_dir/mangosteen-*.tar.gz;

title '打包源代码'
# 打包排除目录
tar --exclude="tmp/cache/*" --exclude="tmp/deploy_cache/*" --exclude="vendor/*" -cz -f $dist *
echo "源代码已打包为 $dist"
###
title "打包本地依赖 ${vendor_1}"
bundle cache --quiet
tar -cz -f "$vendor_dir/cache.tar.gz" -C ./vendor cache
tar -cz -f "$vendor_dir/$vendor_1.tar.gz" -C ./vendor $vendor_1
echo "本地依赖已打包为 $vendor_dir/cache.tar.gz 和 $vendor_dir/$vendor_1.tar.gz"
###
title '创建远程目录'
echo "已创建远程目录 $deploy_dir"
mkdir -p $deploy_dir/vendor
###
title '上传源代码和依赖'
cp $dist $deploy_dir/
yes | rm $dist
cp $gemfile $deploy_dir/
cp $gemfile_lock $deploy_dir/
cp $vendor_dir/cache.tar.gz $deploy_dir/vendor/
yes | rm $vendor_dir/cache.tar.gz
cp $vendor_dir/$vendor_1.tar.gz $deploy_dir/vendor/
yes | rm $vendor_dir/$vendor_1.tar.gz
echo "源代码和依赖已上传至 $deploy_dir"
echo "包含文件 $gemfile, $gemfile_lock, $vendor_dir/cache.tar.gz, $vendor_dir/$vendor_1.tar.gz"
###
title '上传 Dockerfile'
cp $current_dir/../config/host.Dockerfile $deploy_dir/Dockerfile
echo "Dockerfile 已上传至 $deploy_dir"
###
title '上传 setup 脚本'
cp $current_dir/setup_host.sh $deploy_dir/
echo "setup_host.sh 已上传至 $deploy_dir"
###
title '上传版本号'
echo $time > $deploy_dir/version
echo "版本文件 version 已上传至 $deploy_dir/version"
###
echo '宿主机上传完成,下一步请在宿主机上执行 mangosteen_deploy/setup_host.sh 脚本以完成部署。'
  • 添加可执行权限 chmod +x bin/*.sh
  • 开始执行打包 sh bin/pack_for_host.sh 或者直接 bin/pack_for_host.sh

运行成功显示如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
bin/pack_for_host.sh no
# 检测到有效目录,使用基础路径: /workspaces
rm: cannot remove 'tmp/mangosteen-*.tar.gz': No such file or directory

###############################################################################
## 打包源代码
###############################################################################

tar: tmp/mangosteen-20261203-230409.tar.gz: file changed as we read it
源代码已打包为 tmp/mangosteen-20261203-230409.tar.gz

###############################################################################
## 打包本地依赖 rspec_api_documentation
###############################################################################

Don't run Bundler as root. Installing your bundle as root will break this application for all non-root users on this machine.
本地依赖已打包为 bin/../vendor/cache.tar.gz 和 bin/../vendor/rspec_api_documentation.tar.gz

###############################################################################
## 创建远程目录
###############################################################################

已创建远程目录 /workspaces/oh-my-env-2/mangosteen_deploy

###############################################################################
## 上传源代码和依赖
###############################################################################

源代码和依赖已上传至 /workspaces/oh-my-env-2/mangosteen_deploy
包含文件 bin/../Gemfile, bin/../Gemfile.lock, bin/../vendor/cache.tar.gz, bin/../vendor/rspec_api_documentation.tar.gz

###############################################################################
## 上传 Dockerfile
###############################################################################

Dockerfile 已上传至 /workspaces/oh-my-env-2/mangosteen_deploy

###############################################################################
## 上传 setup 脚本
###############################################################################

setup_host.sh 已上传至 /workspaces/oh-my-env-2/mangosteen_deploy

###############################################################################
## 上传版本号
###############################################################################

版本文件 version 已上传至 /workspaces/oh-my-env-2/mangosteen_deploy/version
宿主机上传完成,下一步请在宿主机上执行 mangosteen_deploy/setup_host.sh 脚本以完成部署。

本地容器初始化脚本 bin/setup_host.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/bin/bash

# setup_host.sh 初始化容器,配置为 host.Dockerfile

# 声明变量,注意在 docker 命令中,需要添加前缀 $ 使用
root=mangosteen_deploy
version=$(cat $root/version)
container_name=mangosteen-prod-1
db_container_name=db-for-mangosteen-host-prod
DB_HOST=$db_container_name
DB_PASSWORD=123456
HOST_PROD_PORT=3001

function set_env {
  name=$1
  hint=$2
  [[ ! -z "${!name}" ]] && return
  while [ -z "${!name}" ]; do
    [[ ! -z "$hint" ]] && echo "> 请输入 $name: $hint" || echo "> 请输入 $name:"
    read $name
  done
  sed -i "1s/^/export $name=${!name}\n/" ~/.bashrc
  echo "${name} 已保存至 ~/.bashrc"
}

function title {
  echo
  echo "###############################################################################"
  echo "## $1"
  echo "###############################################################################"
  echo
}

###
title '设置远程机器的环境变量'
set_env DB_HOST
set_env DB_PASSWORD
set_env RAILS_MASTER_KEY '请将 config/credentials/production.key 的内容复制到这里'
echo "已成功设置数据库名称 $DB_HOST, 数据库密码 *******, 加密密钥 *******"
###
title '创建数据库'
if [ "$(docker ps -aq -f name=^${DB_HOST}$)" ]; then
  echo "数据库 $DB_HOST 已存在"
else
  docker run -d --name $DB_HOST \
            --network=network1 \
            -e POSTGRES_USER=mangosteen \
            -e POSTGRES_DB=mangosteen_production \
            -e POSTGRES_PASSWORD=$DB_PASSWORD \
            -e PGDATA=/var/lib/postgresql/data/pgdata \
            -v mangosteen-data:/var/lib/postgresql/data \
            postgres:14
  echo "数据库 $DB_HOST 已创建成功"
fi
###
title 'docker build'
docker build $root -t mangosteen:$version
echo "镜像 mangosteen:$version 已构建成功"
if [ "$(docker ps -aq -f name=^mangosteen-prod-1$)" ]; then
  title 'docker rm'
  docker rm -f $container_name
  echo "旧容器 $container_name 已删除"
fi
###
title 'docker run'
docker run -d -p $HOST_PROD_PORT:3000 \
          --network=network1 \
          --name=$container_name \
          -e DB_HOST=$DB_HOST \
          -e DB_PASSWORD=$DB_PASSWORD \
          -e RAILS_MASTER_KEY=$RAILS_MASTER_KEY \
          mangosteen:$version
echo "容器 $container_name 已运行成功,宿主机端口:容器端口,已映射为 $HOST_PROD_PORT:3000"
###
echo "是否要更新数据库?[y/N]"
read ans
case $ans in
    y|Y|1  )  echo "yes"; title '更新数据库'; docker exec $container_name bin/rails db:create db:migrate ;;
    n|N|2  )  echo "no" ;;
    ""     )  echo "no" ;;
esac

title "全部执行完毕,确认是否正确配置 force_ssl,请访问宿主机端口 curl -v http://localhost:$HOST_PROD_PORT"
  • 进入目录 cd oh-my-env2/,运行 RAILS_MASTER_KEY=xxx mangosteen_deploy/setup_host.sh
  • 可用来测试的 curl 命令
    • curl --noproxy "*" -v http://localhost:3000
    • curl --noproxy "*" -v --data "email=xxx@163.com" http://localhost/api/v1/validation_codes

修改远程打包、远程初始化脚本 ⇧

``


注意本地/远程生产环境服务器启动 puma 默认使用 https ⇧

目前暂时未配置 nginx

  • 访问 curl --noproxy "*" -v http://xxx.xxx.xxx.xxx:3000
  • 访问 curl --noproxy "*" -v --data "email=example@example.com" http://xxx.xxx.xxx.xxx:3000/api/v1/validation_codes
  • 都会重定向到 https://xxx.xxx.xxx.xxx:3000 返回 HTTP/1.1 308 Permanent Redirect

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    
    curl --noproxy "*" -v http://xxx.xxx.xx.xxx:3000
    * !!! WARNING !!!
    * This is a debug build of libcurl, do not use in production.
    *   Trying xxx.xxx.xx.xxx:3000...
    * Established connection to xxx.xxx.xx.xxx (xxx.xxx.xx.xxx port 3000) from yyy.yyy.yy.yyy port 64200
    * using HTTP/1.x
    * sending last upload chunk of 83 bytes
    * Curl_xfer_send(len=83, eos=1) -> 0, 83
    > GET / HTTP/1.1
    > Host: xxx.xxx.xx.xxx:3000
    > User-Agent: curl/8.22.0
    > Accept: */*
    >
    * Request completely sent off
    < HTTP/1.1 301 Moved Permanently
    < content-type: text/html; charset=utf-8
    < location: https://xxx.xxx.xx.xxx:3000/
    < content-length: 0
    <
    * Connection #0 to host xxx.xxx.xx.xxx:3000 left intact
    
    curl --noproxy "*" -v --data "email=example@example.com" http://xxx.xxx.xx.xxx:3000/api/v1/validation_codes
    * !!! WARNING !!!
    * This is a debug build of libcurl, do not use in production.
    *   Trying xxx.xxx.xx.xxx:3000...
    * Established connection to xxx.xxx.xx.xxx (xxx.xxx.xx.xxx port 3000) from yyy.yyy.yy.yyy port 59409
    * using HTTP/1.x
    * sending last upload chunk of 198 bytes
    * Curl_xfer_send(len=198, eos=1) -> 0, 198
    > POST /api/v1/validation_codes HTTP/1.1
    > Host: xxx.xxx.xx.xxx:3000
    > User-Agent: curl/8.22.0
    > Accept: */*
    > Content-Length: 22
    > Content-Type: application/x-www-form-urlencoded
    >
    * upload completely sent off: 22 bytes
    < HTTP/1.1 308 Permanent Redirect
    < content-type: text/html; charset=utf-8
    < location: https://xxx.xxx.xx.xxx:3000/api/v1/validation_codes
    < content-length: 0
    <
    * Connection #0 to host xxx.xxx.xx.xxx:3000 left intact

可临时设置 config/environments/production.rb 使用 http

  • 可临时设置 config.force_ssl = false
  • 设置完成后重新运行 bin/pack_for_remote.sh
  • 成功启动远程服务器中容器,查看 docker ps

    1
    2
    3
    
    CONTAINER ID   IMAGE                        COMMAND                  CREATED             STATUS          PORTS                                         NAMES
    a271b1cadd03   mangosteen:20261203-215525   "bundle exec puma"       33 minutes ago      Up 33 minutes   0.0.0.0:3000->3000/tcp, [::]:3000->3000/tcp   mangosteen-prod-1
    e8dc4cd50506   postgres:14                  "docker-entrypoint.s…"   About an hour ago   Up 49 minutes   5432/tcp                                      db-for-mangosteen
  • 再次访问 curl --noproxy "*" -v http://xxx.xxx.xxx.xxx:3000

    • 返回 HTTP/1.1 401 Unauthorized
  • 再次访问 curl --noproxy "*" -v --data "email=example@example.com" http://xxx.xxx.xxx.xxx:3000/api/v1/validation_codes

    • 返回 HTTP/1.1 200 OK
    • 多次访问返回 HTTP/1.1 429 Too Many Requests
  • 说明服务启动成功

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    
    curl --noproxy "*" -v http://xxx.xxx.xx.xxx:3000
    * !!! WARNING !!!
    * This is a debug build of libcurl, do not use in production.
    *   Trying xxx.xxx.xx.xxx:3000...
    * Established connection to xxx.xxx.xx.xxx (xxx.xxx.xx.xxx port 3000) from yyy.yyy.yy.yyy port 58204
    * using HTTP/1.x
    * sending last upload chunk of 83 bytes
    * Curl_xfer_send(len=83, eos=1) -> 0, 83
    > GET / HTTP/1.1
    > Host: xxx.xxx.xx.xxx:3000
    > User-Agent: curl/8.22.0
    > Accept: */*
    >
    * Request completely sent off
    < HTTP/1.1 401 Unauthorized
    < cache-control: no-cache
    < x-request-id: 74cbe4b8-bac0-4f06-aa42-1009bdef92b0
    < x-runtime: 0.001077
    < content-length: 26
    <
    {"reason":"Token Invalid"}* Connection #0 to host xxx.xxx.xx.xxx:3000 left intact
    
    curl --noproxy "*" -v --data "email=example@example.com" http://xxx.xxx.xx.xxx:3000/api/v1/validation_codes
    *   Trying xxx.xxx.xx.xxx:3000...
    * Established connection to xxx.xxx.xx.xxx (xxx.xxx.xx.xxx port 3000) from 172.24.31.15 port 41024
    * using HTTP/1.x
    > POST /api/v1/validation_codes HTTP/1.1
    > Host: xxx.xxx.xx.xxx:3000
    > User-Agent: curl/8.18.0
    > Accept: */*
    > Content-Length: 22
    > Content-Type: application/x-www-form-urlencoded
    >
    * upload completely sent off: 22 bytes
    < HTTP/1.1 200 OK
    < x-frame-options: SAMEORIGIN
    < x-xss-protection: 0
    < x-content-type-options: nosniff
    < x-permitted-cross-domain-policies: none
    < referrer-policy: strict-origin-when-cross-origin
    < content-type: text/plain; charset=utf-8
    < vary: Accept
    < etag: W/"36a9e7f1c95b82ffb99743e0c5c4ce95"
    < cache-control: max-age=0, private, must-revalidate
    < x-request-id: 4e45621a-75fd-45db-a814-1544fa637b00
    < x-runtime: 0.096088
    < content-length: 1
    <
    * Connection #0 to host xxx.xxx.xx.xxx:3000 left intact
    root@iZ2zegvizksa4gcl6idbmtZ:~# curl --noproxy "*" -v --data "email=example@example.com" http://xxx.xxx.xx.xxx:3000/api/v1/validation_codes
    *   Trying xxx.xxx.xx.xxx:3000...
    * Established connection to xxx.xxx.xx.xxx (xxx.xxx.xx.xxx port 3000) from 172.24.31.15 port 41026
    * using HTTP/1.x
    > POST /api/v1/validation_codes HTTP/1.1
    > Host: xxx.xxx.xx.xxx:3000
    > User-Agent: curl/8.18.0
    > Accept: */*
    > Content-Length: 22
    > Content-Type: application/x-www-form-urlencoded
    >
    * upload completely sent off: 22 bytes
    < HTTP/1.1 429 Too Many Requests
    < x-frame-options: SAMEORIGIN
    < x-xss-protection: 0
    < x-content-type-options: nosniff
    < x-permitted-cross-domain-policies: none
    < referrer-policy: strict-origin-when-cross-origin
    < content-type: text/plain; charset=utf-8
    < vary: Accept
    < cache-control: no-cache
    < x-request-id: 77cd36fe-a692-439a-8516-20850ba11a1e
    < x-runtime: 0.005346
    < content-length: 1
    <
    * Connection #0 to host xxx.xxx.xx.xxx:3000 left intact

马上修改回 config.force_ssl = true

  • 重新运行 bin/pack_for_remote.sh

3. 部署API文档 ⇧

``


4. Rails 应用重新创建密钥 ⇧

创建密钥分两种情况:

  • 如果你想保留之前创建的 config/master.key 和 config/credentials.yml.enc 两个文件
    • 就直接把之前的文件复制到本项目的 config 里。
  • 如果你之前没有创建过 config/master.key 和 config/credentials.yml.enc 两个文件,就按下面的步骤做:

    1
    2
    3
    
    rm config/credentials.yml.enc
    # EDITOR="code --wait" rails credentials:edit # 旧版
    VISUAL="code --wait" rails credentials:edit
  • 新版运行 VISUAL="code --wait" rails credentials:edit

  • 注意,如果是生产环境,你就在 credentials:edit 后面加上 --environment production 参数

  • 然后,在打开的文件中写入如下内容(其中 xxx 应该是一串密码或者一串随机字符串,具体怎么生成 xxx 要看对应的视频,不记得就回看一下自己的笔记):

    1
    2
    3
    
    secret_key_base: xxx
    email_password: xxx
    hmac_secret: xxx
  • 这样,就得到了 config/master.key 和config/credentials.yml.enc 两个文件

  • 此时应该提交代码。然后开始写新的代码


5. $3 ⇧

``


6. $3 ⇧

``


7. 可能的报错信息 ⇧

密钥相关报错

  • 拿到代码后,可能需要重新创建密钥:https://docs.qq.com/doc/DU3ByQXZWbFpQRHND 。
  • 这一步是可选的,但如果遇到 ActiveSupport::MessageEncryptor::InvalidMessage 报错,那么你就必须重新创建密钥了。

8. 重要:pack_for_remote.sh 参数更新 ⇧

  • 由于 pack_for_remote.sh 更新了,所以你第一次部署到生产环境时,一定要加 need_migrate=1 前缀,如下:

    1
    
    need_migrate=1 bin/pack_for_remote.sh
  • 加了 need_migrate=1 就会 migrate 数据库,不加就不会 migrate 数据库!切记!


启动容器时报错 ⇧

如果你的报错内容含有

1
ActiveSupport::MessageEncryptor::InvalidMessage (ActiveSupport::MessageEncryptor::InvalidMessage)
  • 那么大概率是生产环境的 config/credentials/production.yml.enc 与 config/credentials/production.key 不匹配
  • 要确定是不是不匹配,只需要运行:

    1
    2
    
    EDITOR="code --wait" bin/rails credentials:edit --environment production
    VISUAL="code --wait" bin/rails credentials:edit --environment production
  • 如果报错,则说明确实不匹配

  • 此时你只能删除 config/credentials/production.yml.enc 与 config/credentials/production.key

  • 然后重新运行:

    1
    2
    
    EDITOR="code --wait" bin/rails credentials:edit --environment production
    VISUAL="code --wait" bin/rails credentials:edit --environment production
  • 这样就能得到两个全新的、匹配的 config/credentials/production.yml.enc 与 config/credentials/production.key 文件。

  • 然后你需要手动将 config/credentials/production.key 的内容更新到远程服务器的 bashrc 的变量 RAILS_MASTER_KEY 中。


·未完待续·

参考文章

相关文章


  • 作者: Joel
  • 文章链接:
  • 版权声明
  • 非自由转载-非商用-非衍生-保持署名