小白阿里云部署rails视频教程-centOS

前言:本人在阿里云部署rails的过程中,踩到了很多坑。 后来,在网友imtinge的帮助下,终于部署成功。

新手在使用教程的过程中,常常会遇到问题:教程上要求,需要修改某个文件,但是,新手根本不知道文件在什么地方。 所有,我部署成功后,录制了这个视频,希望对新手有所帮助。

感谢imtinge帮我写教程,debug, 感谢ruby-China上热心网友jicheng1014, kikyous,tim_lang, yingce, nouse,ringokun, huacnlee, chenge的热心帮助。

这篇教程是imtinge写的,我做了一点点优化。 教程原地址: https://forum.qzy.camp/t/rails/1852, 版权归原作者imtinge所有。

优酷视频网址:
第一部分:http://v.youku.com/v_show/id_XMjg2NDcyNzAxMg==.html?spm=a2h0j.8191423.module_basic_relation.55!255!455A
第二部分:http://v.youku.com/v_show/id_XMjg2NDczMzA4NA==.html?spm=a2h3j.8428770.3416059.1#paction
第三部分:http://v.youku.com/v_show/id_XMjg2NDc0Mjk4NA==.html?spm=a2h0j.8191423.module_basic_relation.55!255!555A
第四部分:http://v.youku.com/v_show/id_XMjg2NDc0ODI4MA==.html?spm=a2h0j.8191423.module_basic_relation.55!255!35!213~A

系统信息:
本地: MacOS Sierra version: 10.12.3
ECS云服务器: centOS 7.3, 64位
域名: eyulaodu

一.更新系统

yum install -y epel-release yum-utils
yum-config-manager --enable epel
yum clean all && sudo yum update -y

二,安装开发工具、nginx和postgresql

  1. 安装
yum groupinstall -y 'development tools'
yum install -y nginx
yum install -y postgresql-server postgresql-contrib postgresql-devel
  1. 启动nginx
systemctl start nginx
systemctl enable nginx

此时,打开绑定的域名,应该能够看到“Welcome to nginx on Fedora!”的欢迎画面。
如果此时没有出现欢迎页面,很可能是阿里云的80端口没打开。
打开阿里云80端口教程
3 . 配置启动postgresql

postgresql-setup initdb
vim /var/lib/pgsql/data/pg_hba.conf

4 . 把

host    all             all             127.0.0.1/32            ident
host    all             all             ::1/128                 ident

改成

host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5

5 . 启动并设置开机启动

systemctl start postgresql
systemctl enable postgresql

6 . 创建用户和库
请把myproject,myprojectuser,password替换为自己的数据库名,数据库用户名和密码

su - postgres
psql
CREATE DATABASE eyulaodu;      (myproject = eyulaodu)
CREATE USER duzilong WITH PASSWORD '111111';
GRANT ALL PRIVILEGES ON DATABASE eyulaodu TO duzilong;
\q
exit

7 . 安装nodejs,assets precompile需要使用

yum install -y nodejs

三、创建发布使用的用户,并配置zsh

  1. 创建用户
useradd -r -m apps
gpasswd -a apps wheel
  1. 设置密码:
passwd apps
  1. 安装ZSH
sudo yum install zsh
  1. 安装oh my zsh
su - apps
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

exit回到root目录下,运行

yum install -y openssl-devel readline-devel zlib-devel

5 . 在su - apps 下

git clone https://github.com/rbenv/rbenv.git ~/.rbenv
cd ~/.rbenv && src/configure && make -C src
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.zshrc
~/.rbenv/bin/rbenv init
echo 'eval "$(rbenv init -)"' >> ~/.zshrc
su - apps
rbenv install 2.4.1                 (备注:此处时间较长,耐心等待,大概花了5分钟安装)
rbenv global 2.4.1
gem install bundler 
gem install rails         (本处花的时间多点,6分钟左右)

6 . 创建发布使用的目录(需要用exit 回到根目录下)

exit
exit
mkdir /var/www
chown apps:apps /var/www

------------------------分割线,本机部分-----------------------------

四、本地文件配置

  1. 假设你的项目已经完成
    编辑Gemfile,增加
gem 'mina', require: false
gem 'mina-puma', require: false
  1. bundle install
  2. 编辑.gitignore,确保你的database.yml, puma.rb, secrets.yml不在git控制之内
config/secrets.yml
config/database.yml
config/puma.rb
  1. touch config/deploy.rb
    加入以下内容(注意:第14到17行,的内容要修改为自己专案的信息)
require 'mina/bundler'
require 'mina/rails'
require 'mina/git'
require 'mina/puma'
require 'mina/rbenv'  # for rbenv support. (https://rbenv.org)
# require 'mina/rvm'    # for rvm support. (https://rvm.io)

# Basic settings:
#   domain       - The hostname to SSH to.
#   deploy_to    - Path to deploy into.
#   repository   - Git repo to clone from. (needed by mina/git)
#   branch       - Branch name to deploy. (needed by mina/git)

set :application_name, 'eyulaodu'
set :domain, '[email protected]'
set :deploy_to, '/var/www/eyulaodu'
set :repository, 'https://github.com/hofffmancx/eyulaodu.git'
set :branch, 'master'

# Optional settings:
#   set :user, 'foobar'          # Username in the server to SSH to.
#   set :port, '30000'           # SSH port number.
#   set :forward_agent, true     # SSH forward_agent.

# shared dirs and files will be symlinked into the app-folder by the 'deploy:link_shared_paths' step.
set :shared_dirs, fetch(:shared_dirs, []).push('log', 'tmp/pids', 'tmp/sockets', 'public/uploads')
set :shared_files, fetch(:shared_files, []).push('config/database.yml', 'config/secrets.yml', 'config/puma.rb')

# This task is the environment that is loaded for all remote run commands, such as
# `mina deploy` or `mina rake`.
task :environment do
  # If you're using rbenv, use this to load the rbenv environment.
  # Be sure to commit your .ruby-version or .rbenv-version to your repository.
  invoke :'rbenv:load'

  # For those using RVM, use this to load an RVM version@gemset.
  # invoke :'rvm:use', 'ruby-1.9.3-p125@default'
end

# Put any custom commands you need to run at setup
# All paths in `shared_dirs` and `shared_paths` will be created on their own.
task :setup do
  # command %{rbenv install 2.3.0}
  command %[touch "#{fetch(:shared_path)}/config/database.yml"]
  command %[touch "#{fetch(:shared_path)}/config/secrets.yml"]
  command %[touch "#{fetch(:shared_path)}/config/puma.rb"]
  comment "Be sure to edit '#{fetch(:shared_path)}/config/database.yml', 'secrets.yml' and puma.rb."
end

desc "Deploys the current version to the server."
task :deploy do
  # uncomment this line to make sure you pushed your local branch to the remote origin
  # invoke :'git:ensure_pushed'
  deploy do
    comment "Deploying #{fetch(:application_name)} to #{fetch(:domain)}:#{fetch(:deploy_to)}"
    # Put things that will set up an empty directory into a fully set-up
    # instance of your project.
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'rails:assets_precompile'
    invoke :'deploy:cleanup'

    on :launch do
      in_path(fetch(:current_path)) do
        command %{mkdir -p tmp/}
        command %{touch tmp/restart.txt}
        invoke :'puma:restart'
      end
    end
  end

  # you can use `run :local` to run tasks on local machine before of after the deploy scripts
  # run(:local){ say 'done' }
end

# For help in making your deploy script, see the Mina documentation:
#
#  - https://github.com/mina-deploy/mina/tree/master/docs

5 . 编辑config/initializers/devise.rb. 在最后一个end前,加入

config.secret_key = ENV['DEVISE_SECRET_KEY']

6 . commit

git add . 
git commit -m "change secret_key"
git push origin ch09

7 . mina setup

------------------------分割线,又连上主机-----------------------------

六、数据库及服务器配置

  1. 设置数据库信息
    cd /var/www/eyulaodu/shared/config
    vim database.yml
    (这个文件,打开的时候,没有内容)
production: 
  adapter: postgresql 
  pool: 5 
  timeout: 5000 
  encoding: utf8 
  host: localhost 
  database: eyulaodu 
  username: duzilong 
  password: <%= ENV['eyulaodu_DATABASE_PASSWORD'] %>

production:
adapter: postgresql
pool: 5
timeout: 5000
encoding: utf8
host: localhost
database: jdstoredzlm
username: duzilong
password: <%= ENV['jdstoredzlm_DATABASE_PASSWORD'] %>

2 .设置服务器信息
vim puma.rb
(这个文件,打开的时候,没有内容)

environment "production"

workers 1
threads 1,5

application_path = File.expand_path('../..', __dir__)

directory "#{application_path}/current"

pidfile "#{application_path}/shared/tmp/pids/puma.pid"
state_path "#{application_path}/shared/tmp/sockets/puma.state"
stdout_redirect "#{application_path}/shared/log/puma.stdout.log", "#{application_path}/shared/log/puma.stderr.log"

bind "unix://#{application_path}/shared/tmp/sockets/puma.sock"

activate_control_app "unix://#{application_path}/shared/tmp/sockets/pumactl.sock"

daemonize true
preload_app!

3 . vim secrets.yml
(这个文件,打开的时候,没有内容)

production: 
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

4 .
退回根目录,然后:
cd
su - apps
vim ~/.zshenv
(这个文件,打开的时候,没有内容)
密码自己设置,key通过rake secret生成(在project的目录下)

export SECRET_KEY_BASE='de6c01c619dfe9e0bc4d0c16c30cdcd86aca400598ba48d72d7c1fc36180dee6e822da3df956ded9631017a2e1dd14d64c9ec3f78c7aff40f1f0e66f41735912'
export eyulaodu_DATABASE_PASSWORD='111111'
export DEVISE_SECRET_KEY='de6c01c619dfe9e0bc4d0c16c30cdcd86aca400598ba48d72d7c1fc36180dee6e822da3df956ded9631017a2e1dd14d64c9ec3f78c7aff40f1f0e66f41735912'

5 .切回root
exit
6 . vim /etc/nginx/nginx.conf
注释以下内容(在include /etc/nginx/conf.d/*.conf;下面)

#     server {
#         listen       80 default_server;
#         listen       [::]:80 default_server;
#         server_name  _;
#         root         /usr/share/nginx/html;
#
#         # Load configuration files for the default server block.
#         include /etc/nginx/default.d/*.conf;
#
#         location / {
#         }
#
#         error_page 404 /404.html;
#             location = /40x.html {
#         }
#
#         error_page 500 502 503 504 /50x.html;
#             location = /50x.html {
#         }
#     }

7 . 新增touch /etc/nginx/conf.d/eyulaodu.conf,请注意和puma里面文件的设置一致
vim /etc/nginx/conf.d/eyulaodu.conf

upstream app {
    # Path to Unicorn SOCK file, as defined previously
    server unix:/var/www/eyulaodu/shared/tmp/sockets/puma.sock fail_timeout=0;
}

server {


    listen 80;
    server_name eyulaodu.com;

    # Application root, as defined previously
    root /var/www/eyulaodu/current/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app;
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}

8 . 重启nginx
systemctl restart nginx

--------------------又回到本机—————————————————
七、 本机自动部署网站

1 . 进入你的项目目录
mina deploy
mina puma:start

打开你的域名,出现页面成功。

2 . 以后更新发布只需要提交后执行

mina deploy
即可


备注:

  1. VIM 编辑器的基本用法:
    vim 文件名 进入文档
    i 进入编辑状态
    esc 取消编辑状态
    ZZ 保存后退出
  2. GitHub: https://github.com/hofffmancx/eyulaodu

你可能感兴趣的:(小白阿里云部署rails视频教程-centOS)