wsblogs / rails

0 stars 0 forks source link

Capstrano部署rails项目 #2

Open wuyuedefeng opened 6 months ago

wuyuedefeng commented 6 months ago

基础命令

$ apt-get update  

添加SSH 到服务器

$ cd ~
$ mkdir .ssh
$ cd .ssh
$ vim authorized_keys # 将本机id_rsa.pub中的key粘贴进去

服务器生成ssh key

$ ssh-keygen -t rsa -b 4096 -C "xiaoyaer.zezeping.com"
# 将生成的 ~/.ssh/id_id_rsa.pub 密钥放到git部署目录中: https://github.com/zezeping/xiaoyaer/settings/keys/new

安装git

$ sudo apt-get install git

安装nginx

[sudo] apt-get update  
[sudo] apt-get install nginx

配置文件

# (配置文件生效所在目录:/etc/nginx/sites-enabled/)
# cd /etc/nginx/sites-available
upstream xiaoyaer-backend {
    server unix:///mnt/www/xiaoyaer/backend/shared/tmp/sockets/puma.sock;
  }
server {
  listen 80;
  server_name xiaoyaer.zezeping.com;
  root /mnt/www/xiaoyaer/backend/shared/public; # I assume your app is located at that location
  location ^~ /api/ {
    proxy_pass http://xiaoyaer-backend/; # match the name of upstream directive which is defined above
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
  location ^~ /cable {
    proxy_pass http://xiaoyaer-backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
  }
  location ~* ^/assets/ {
    # Per RFC2616 - 1 year maximum expiry
    expires 1y;
    add_header Cache-Control public;

    # Some browsers still send conditional-GET requests if there's a
    # Last-Modified header or an ETag header even if they haven't
    # reached the expiry date sent in the Expires header.
    add_header Last-Modified "";
    add_header ETag "";
    break;
  }
}
# sudo ln -sf /etc/nginx/sites-available/xiaoyaer.conf /etc/nginx/sites-enabled/xiaoyaer.conf

启动报错可以执行下面命令,会打印出错误信息(个人测试)

$ sudo nginx -t -c /etc/nginx/nginx.conf

重启nginx服务

sudo service nginx reload

安装node

# sudo apt install -y curl
# 安装16.x版本
# curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash - 
# 安装20.x版本
# curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - 
sudo apt-get install nodejs

安装Redis

$ sudo  apt-get install redis-server
# service  redis status
# 设置密码: 找到/et/redis/redis.conf文件修改如下   ,添加  requirepass kingredis(密码设置为kingredis)
# 测试连接: 如果是阿里云服务器,切记要在安全组、安全策略里面加入服务的端口号,允许所有地址访问,如下图,才可以,即在阿里云服务器的所有服务都需要把端口映射出来才可以,如果没有做这一步,上面的redis-cli命令就会处于一直等待的状态

安装rbenv

安装ruby

$ sudo apt install git curl libssl-dev libreadline-dev zlib1g-dev autoconf bison build-essential libyaml-dev libreadline-dev libncurses5-dev libffi-dev libgdbm-dev

$ rbenv install 3.2.3
$ rbenv versions
$ rbenv local 3.2.3
$ gem install bundler

Capstrano部署

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

# Include default deployment tasks
require "capistrano/deploy"

require "capistrano/rails"

# 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::Systemd

# 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.18.1"

set :rails_env, 'production'

set :rbenv_type, :deploy # or :system, depends on your rbenv setup
set :rbenv_ruby, File.read('.ruby-version').strip

set :application, "xiaoyaer-backend"
set :repo_url, "git@github.com:zezeping/xiaoyaer.git"
# rails在git仓库中的相对路径 https://capistranorb.com/documentation/getting-started/configuration/
set :repo_tree, 'backend'

# 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, "/mnt/www/xiaoyaer/backend"

# 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", 'config/master.key'
append :linked_files, "config/database.yml", "config/application.yml", "config/master.key", "config/puma.rb"

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

# 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
set :ssh_options, verify_host_key: :never

set :puma_conf, "#{shared_path}/config/puma.rb"

before 'deploy:migrate', 'db:create'
namespace :db do
  desc 'Create Database'
  task :create do
    on roles(:db) do |host|
      within release_path do
        with rails_env: fetch(:rails_env) do
          execute :rails, 'db:create'
        end
      end
    end
  end
end
# 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}

# root执行有警告,修复需要服务器设置: bundle config --global silence_root_warning true
server "47.116.79.16", user: "root", roles: %w{app db}
set :branch, :main

# 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/user_name/.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
# /mnt/www/xiaoyaer/backend/shared/config/master.key
# /mnt/www/xiaoyaer/backend/shared/config/database.yml
# /mnt/www/xiaoyaer/backend/shared/config/application.yml 
# server 
# /mnt/www/xiaoyaer/backend/shared/config/puma.rb
#!/usr/bin/env puma
app_name = "backend"
app_path = "/mnt/www/xiaoyaer/#{app_name}"

environment "production"
workers 2
threads 1,16

directory "#{app_path}/current"

bind "unix://#{app_path}/shared/tmp/sockets/puma.sock"
pidfile "#{app_path}/shared/tmp/pids/puma.pid"
state_path "#{app_path}/shared/tmp/pids/puma.state"
stdout_redirect "#{app_path}/shared/log/puma.stdout.log", "#{app_path}/shared/log/puma.stderr.log"
activate_control_app "unix://#{app_path}/shared/tmp/sockets/pumactl.sock"

on_restart do
  puts 'On restart...'
end
prune_bundler
$ cap staging setup
$ cap staging deploy:check
$ cap staging puma:systemd:config
$ cap staging deploy

其他相关文章

wuyuedefeng commented 6 months ago

install Postgresql

$ sudo apt update -y
$ sudo apt install gnupg2 wget vim -y
$ sudo sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
$ curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc|sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/postgresql.gpg
$ sudo apt update -y
# 要安装最新的可用版本,请运行: sudo apt-get -y install postgresql postgresql-contrib
$ sudo apt install postgresql-16
$ sudo apt install libpq-dev

$ sudo systemctl start postgresql
$ sudo systemctl enable postgresql
$ systemctl status postgresql

# 检查已安装的 PostgreSQL 版本
$ psql --version
# 您还可以使用以下命令检查版本
$ sudo -u postgres psql -c "SELECT version();"

- Connection Settings -

listen_addresses = '*' # what IP address(es) to listen on;

comma-separated list of addresses;

                                    # defaults to 'localhost'; use '*' for all

* 继续并使用以下命令允许密码身份验证

$ sudo sed -i '/^host/s/ident/md5/' /etc/postgresql/16/main/pg_hba.conf


* 将识别方法从对等更改为信任

$ sudo sed -i '/^local/s/peer/trust/' /etc/postgresql/16/main/pg_hba.conf


* 编辑以下行允许远程访问 PostgreSQL

$ sudo vim /etc/postgresql/16/main/pg_hba.conf

IPv4 local connections:

host all all 127.0.0.1/32 scram-sha-256 host all all 0.0.0.0/0 scram-sha-256

IPv6 local connections:

host all all ::1/128 scram-sha-256 host all all 0.0.0.0/0 md5


* 保存所做的更改并重新启动服务

$ sudo systemctl restart postgresql


* 如果启用了防火墙,请允许 PostgreSQL 端口通过

$ sudo ufw allow 5432/tcp


* 连接到 PostgreSQL 16
```bash
# 方法一: 直接连接PosgreSQL
$ sudo -u postgres psql
# 方法二:切换到Postgres用户
$ sudo -i -u postgres
# 然后连接到实例
$ psql
# 您可以使用以下命令从客户端远程连接到 PostgreSQL
$ psql 'postgres://<username>:<password>@<host>:<port>/<db>?sslmode=disable'

PostgreSQL 16 入门

测试密码是否有效

$ psql -h localhost -U postgres


* 在 PostgreSQL 上创建用户
```bash
CREATE ROLE admin WITH LOGIN SUPERUSER CREATEDB CREATEROLE PASSWORD 'Passw0rd';

# 验证用户创建
postgres=# \du


---
参考文章
* https://cn.linux-console.net/?p=22460