Railsアプリをgit pushでデプロイする

以前作ったSumtimerをわけあってHerokuからAWS(EC2+RDS)に移したんだけど、git pushでのdeployは気に入ってたので頑張って設定した。その作業メモ。

やりたいこと

Railsアプリ(awesome-app)を、
Git Repository(git@example.com:awesome-app.git)にpushしたら、
自動的にhttp://awesome-app.example.com/にデプロイされる

手順

  1. サーバにユーザ’git’を作って公開鍵でsshログインできるようにしておく
  2. [bash]
    # サーバ側(example.com)での作業
    # 事前にローカルPCの公開鍵(ここではid_rsa.pub)をRemoteの適当なところにコピーしておく
    sudo useradd -m -s /bin/bash git
    sudo su git
    mkdir /home/git/.ssh
    cat id_rsa.pub >> /home/git/.ssh/authorized_keys
    [/bash]

  3. push先のリポジトリを作る
  4. [bash]
    # サーバ側(example.com)での作業。gitでログイン中。
    mkdir ~/awesome-app.git
    cd ~/awesome-app.git
    git init –bare
    [/bash]

  5. 作ったリポジトリをリモートリポジトリとして登録しておく
  6. [bash]
    # ローカルPC上での作業
    git remote add production git@example.com:awesome-app.git
    [/bash]

  7. デプロイ先を作る。
  8. [bash]
    # サーバ側(example.com)での作業。gitでログイン中
    mkdir ~/deployed
    cd ~/deployed
    git clone ~/awesome-app.git
    [/bash]

  9. http://awesome-app.example.com/がデプロイ先を参照するようにしておく
  10. (例:Apache/Passengerの場合)
    [text]
    <VirtualHost *:80>
    ServerName awesome-app.example.com
    DocumentRoot /home/git/deployed/awesome-app/public
    <Directory /home/git/deployed/awesome-app/public>
    AllowOverride all
    Options -MultiViews
    </Directory>
    </VirtualHost>
    [/text]

  11. git pushにhookを仕掛ける
  12. [bash]
    vi ~/awesome-app.git/hooks/post-receive
    chmod +x ~/awesome-app.git/hooks/post-receive
    [/bash]
    ~/awesome-app.git/hooks/post-receiveの中身はこんな感じ。git pullしてbuild/migrateしてRailsをrestart
    [bash]
    #!/bin/sh
    (
    cd /home/git/deployed/awesome-app &&
    git –git-dir=.git pull &&
    bundle install –path vendor/bundler &&
    RAILS_ENV=production bundle exec rake db:migrate &&
    RAILS_ENV=production bundle exec rake assets:precompile &&
    touch ./tmp/restart.txt
    )
    [/bash]

以上で、git push production masterとやればデプロイされるようになりました。
Herokuみたいにちゃんとやるなら他にも色々やることありそうだけど、とりあえずヤッター!

コメントする