Skip to content

Instantly share code, notes, and snippets.

@Iwark
Last active August 29, 2015 14:05
Show Gist options
  • Save Iwark/e369bd38e8d5b65da129 to your computer and use it in GitHub Desktop.
Save Iwark/e369bd38e8d5b65da129 to your computer and use it in GitHub Desktop.
RaisアプリのAWSへのデプロイ

まずはAWSのインスタンスを作成する

http://iti.hatenablog.jp/entry/2014/05/20/162927 あたりを参考にすればOK。

SSHでAWSに接続できるところまでいったら、以下の感じでコマンドを入力していく。

  • まずはgitとかrubyのインストール
sudo yum update -y

sudo yum install git -y

git clone https://github.com/sstephenson/rbenv.git ~/.rbenv

echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile

echo 'eval "$(rbenv init -)"' >> ~/.bash_profile

source ~/.bash_profile

git clone git://github.com/sstephenson/ruby-build.git

cd ruby-build

sudo ./install.sh

sudo yum install gcc patch gcc-c++ readline readline-devel zlib zlib-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison iconv-devel

cd ~

rbenv install 2.1.2

rbenv global 2.1.2

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

rbenv rehash
  • 必要ならNode.jsもインストール
wget http://nodejs.org/dist/node-latest.tar.gz

tar xfz node-latest.tar.gz

cd node-v(tab complete to the latest version)

./configure && make

sudo make install
  • Nginxのインストール
sudo vi /etc/yum.repos.d/nginx.repo

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/$basearch/
gpgcheck=0
enabled=1

sudo yum install nginx -y
sudo chkconfig nginx on
  • ImageMagick(画像処理する場合)とかsqlite(あるいは他のデータベース)のインストール
sudo yum install ImageMagick ImageMagick-devel -y

sudo yum -y install sqlite-devel
  • アプリの、Nginxの設定を書く。(xxx-xx-xxx-xxxのところなど、自分のインスタンスに沿って設定)
sudo vi /etc/nginx/conf.d/(アプリ名とか).conf

upstream ec2-xxx-xx-xxx-xxx.ap-northeast-1.compute.amazonaws.com {
    server unix:/tmp/unicorn.sock;
}

server {
    listen       80;
    server_name  (github上のアプリ名);
    root         /usr/share/nginx/html;

    location ~ ^/uploads/ {
        root    /home/ec2-user/(github上のアプリ名)/current/public;
        gzip_static on; # to serve pre-gzipped version
        expires 1y;
        add_header Cache-Control public;
        add_header ETag "";
        break;
    }

    location ~ ^/assets/ {
        root     /home/ec2-user/(github上のアプリ名)/current/public;
        gzip_static on; # to serve pre-gzipped version
        expires 1y;
        add_header Cache-Control public;
        add_header ETag "";
        break;
    }

    location / {
        proxy_pass http://ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com;
    }

    # redirect server error pages to the static page /40x.html
    #
    error_page  404              /404.html;
    location = /40x.html {
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    }
}
  • Nginxの起動(または再起動)とパーミッションの変更
sudo service nginx restart

sudo chmod 755 /
chmod 755 ec2-user/

アプリにUnicornとかCapistranoの設定をする。

  • まずはGemfileにこんなのを追記
gem 'unicorn'

group :development do
  gem "capistrano"
  gem "capistrano-rails"
  gem "capistrano-bundler"
  gem "capistrano-rbenv"
  gem "capistrano3-unicorn"
end
  • インストール
bundle install
  • Capistranoの設定ファイルを作成
bundle exec cap install STAGES=staging,production
  • できたCapfileを次の感じに編集
require 'capistrano/setup'

require 'capistrano/deploy'

require 'capistrano/rbenv'
require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
require 'capistrano3/unicorn'

Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
  • configのdeploy.rbを次の感じに編集
lock '3.2.1'

set :application, '(アプリ名)'
set :repo_url, '[email protected]:(Githubのレポジトリ).git'

# Default deploy_to directory is /var/www/my_app
set :deploy_to, '/home/ec2-user/(Gihthub上のアプリ名)'

set :scm, :git

set :rbenv_ruby, '2.1.2'

# Default value for :linked_files is []
# set :linked_files, %w{config/secrets.yml}

set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/assets public/uploads}

set :default_stage, "production"

set :default_env, {
  rbenv_root: "/home/ec2-user/rbenv",
  path: "/home/ec2-user/rbenv/shims:/home/ec2-user/rbenv/bin:$PATH",
  secret_key_base: '(シークレットキー。あらかじめ rake secret コマンドで生成)'
}

# set :linked_dirs, (fetch(:linked_dirs) + ['tmp/pids'])

set :unicorn_rack_env, "production"
set :unicorn_config_path, 'config/unicorn.conf'

namespace :deploy do

  desc 'Restart application'
  task :restart do
    invoke 'unicorn:restart'
  end

  after :publishing, :restart

  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
      # Here we can do anything such as:
      # within release_path do
      #   execute :rake, 'cache:clear'
      # end
    end
  end

end
  • config/deploy/production.rbを作成
role :app, %w{ec2-user@(アプリ名)}
role :web, %w{ec2-user@(アプリ名)}
role :db,  %w{ec2-user@(アプリ名)}

set :stage, :production
set :rails_env, :production
  • ~/.ssh/configを作成
Host (アプリ名)
  HostName (AWSインスタンスのIPアドレス)
  User ec2-user
  Port 22
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile ~/.ssh/AWS-EC2-KEY.pem (AWSでダウンロードしたKEY)
  IdentitiesOnly yes
  ForwardAgent yes
  • Unicornの設定をconfig/unicorn.rbに書く
worker_processes 2
listen '/tmp/unicorn.sock'
pid "tmp/pids/unicorn.pid"
timeout 15
stderr_path File.expand_path('unicorn.log', File.dirname(__FILE__) + '/../log')
stdout_path File.expand_path('unicorn.log', File.dirname(__FILE__) + '/../log')
preload_app true

before_fork do |server, worker|
  defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect!

  old_pid = "#{ server.config[:pid] }.oldbin"
  unless old_pid == server.pid
    begin
      Process.kill :QUIT, File.read(old_pid).to_i
    rescue Errno::ENOENT, Errno::ESRCH
    end
  end
end

after_fork do |server, worker|
  defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection
end
  • デプロイ
bundle exec cap production deploy

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment