Virtual Box インストール
Download
本家 Virtualbox より、 Virtual Box ダウンロード
インストール
Vagrant インストール
Download
本家 Vagrant より、 Vagrantダウンロード
インストール
再起動が必要
仮想マシン(BOX(テンプレート))取得・追加
CnetOS 6.5 用 URL 取得
Vagrantbox.es より、Virtual Box用、CentOS 6.5 x86_64 URLをコピーする
Box add
cd c:\HashiCorp\Vagrant\
mkdir myhost
cd myhost
c:\HashiCorp\Vagrant\myhost> vagrant box add centos65 https://github.com/2creatives/vagrant-centos/releases/download/v6.5.3/centos65-x86_64-20140116.box
==> box: Adding box 'centos65' (v0) for provider:
box: Downloading: https://github.com/2creatives/vagrant-centos/releases/download/v6.5.3/centos65-x86_64-20140116.box
box: Progress: 100% (Rate: 3348k/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'centos65' (v0) for 'virtualbox'!
仮想マシン初期化
c:\HashiCorp\Vagrant\myhost> vagrant init centos65
ブリッジ設定
c:\HashiCorp\Vagrant\myhost\vagrantfile
を編集する
config.vm.network "public_network" # ←アンコメントする
仮想マシン起動
- 仮想マシン起動
c:\HashiCorp\Vagrant\myhost> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos65'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: myhost_default_1421716347228_35069
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Connection timeout. Retrying...
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if its present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
default: /vagrant => C:/HashiCorp/Vagrant/myhost
SSH 接続(TeraTerm で確認)
- アドレス: 127.0.0.1
- ポート: 2222
- ユーザ: vagrant
- パスワード: vagrant
仮想マシン停止
状態確認
c:\HashiCorp\Vagrant\myhost> vagrant status
サスペンド
c:\HashiCorp\Vagrant\myhost> vagrant suspend
終了(電源ぶちぎり)
c:\HashiCorp\Vagrant\myhost> vagrant halt
仮想マシン内でシャットダウン(これがベストっぽい)
$ sudo shutdown -h 00
各種設定
iptables 削除
# 設定削除
$ sudo iptables -F
# 確認
$ sudo iptables -nL
# OKであれば保存
$ sudo /etc/init.d/iptables save
rbenv インストール via anyenv
$ git clone https://github.com/riywo/anyenv ~/.anyenv
$ echo 'export PATH="$HOME/.anyenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(anyenv init -)"' >> ~/.bash_profile
$ exec $SHELL -l
$ anyenv install rbenv
$ exec $SHELL -l
Ruby 2.2.0 インストール
# バージョン一覧は
$ rbenv install -list
# Ruby ビルドで、ビルドエラーが発生するので、 libffi-devel インストール
$ sudo yum install -y libffi-devel
$ rbenv install -v 2.2.0
$ rbenv global 2.2.0
Rails インストール
$ gem update --system
$ gem install rails --no-ri --no-rdoc -V # ドキュメントをインストールしない
$ rbenv rehash
$ rails -v
Nginx インストール
インストール
$ sudo yum install -y nginx
自動起動設定
$ sudo chkconfig --level 35 nginx on
MySQL インストール
インストール
$ sudo yum install -y mysql mysql-server mysql-devel
自動起動設定
$ sudo chkconfig --level 35 mysqld on
Postgresql 9.3
インストール
$ sudo rpm -i http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-redhat93-9.3-1.noarch.rpm
$ sudo yum -y install postgresql93-server postgresql93-contrib postgresql-devel
Postgresql設定
$ sudo service postgresql-9.3 initdb
# 自動起動設定
$ sudo chkconfig postgresql-9.3 on
$ sudo service postgresql-9.3 status
$ sudo service postgresql-9.3 start
# タイムゾーン設定
$ sudo vim /var/lib/pgsql/9.3/data/postgresql.conf
以下に設定
timezone = 'Asia/Tokyo'
Postgresユーザ設定
# 情報確認
$ id postgres
# postgres ユーザパスワード設定
$ sudo passwd postgres
'postgres' 2回入力
$ su - postgres
-- vagrant ユーザを作成
postgres=# create user vagrant createdb password 'vagrant' login;
postgres=# \q
$ exit
Rails App 作成
$ cd /path/to/dir
$ gem install bundler
$ rails new myApp -d postgresql
$ cd myApp
$ vim Gemfile
以下をコメントイン、追記
gem 'therubyracer', platforms: :ruby
...
# Use unicorn as the app server
gem 'unicorn'
# readline 追記
gem 'rb-readline'
インストール
$ bundle install --path vendor/bundle
bundle install --path vendor/bundle
時、Text file busy @ unlink_internal...
なるエラーとなった場合- アプリの格納先が、VMの共有ファイル上となっていないか確認する
- 共有フォルダ内にある場合に発生するエラー
- [小ネタ][Ruby on Rails]bundle install時にText file busy エラー
- アプリの格納先が、VMの共有ファイル上となっていないか確認する
データベース設定
$ vim conifg/database.yml
以下、 utf8 へ変更
default: &default
adapter: postgresql
encoding: utf8 # utf8 へ変更
username: vagrant # vagrant ユーザを指定
password: vagrant # vagrant ユーザパスを指定
Databse作成
$ bundle exec rake db:create
$ bundle exec rails generate scaffold user password:string mail_address:text
...
# などなど、アプリに応じて設定
# db/migrate/ 配下の DB作成処理も合わせて修正
# DB作成
$ bundle exec rake db:migrate
# 削除
$ bundle exec rails destroy scaffold user
...
# DB作成しなおし
$ bundle exec rake db:migrate:reset
Unicorn 設定
$ vim conifg/unicorn.rb
設定内容は以下
@app_path = '/path/to/dir/myApp'
worker_processes 2
working_directory "#{@app_path}/"
# This loads the application in the master process before forking
# worker processes
# Read more about it here:
# http://unicorn.bogomips.org/Unicorn/Configurator.html
preload_app true
timeout 30
# This is where we specify the socket.
# We will point the upstream Nginx module to this socket later on
listen "/tmp/unicorn.sock", :backlog => 64
pid "/tmp/unicorn.pid"
# Set the path of the log files inside the log folder of the testapp
stderr_path "#{@app_path}/log/unicorn.stderr.log"
stdout_path "#{@app_path}/log/unicorn.stdout.log"
before_fork do |server, worker|
defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect!
old_pid = "#{server.config[:pid]}.oldbin"
if old_pid != server.pid
begin
sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
Process.kill(sig, File.read(old_pid).to_i)
rescue Errno::ENOENT, Errno::ESRCH
end
end
sleep 1
end
after_fork do |server, worker|
defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection
end
Nginx 設定
$ sudo mv /etc/nginx/conf.d/default.conf ~
$ sudo vim /etc/nginx/conf.d/myapp.conf
設定内容は以下
upstream unicorn_server {
# This is the socket we configured in unicorn.rb
server unix:/tmp/unicorn.sock
fail_timeout=0;
}
server {
listen 80;
client_max_body_size 4G;
server_name _;
keepalive_timeout 5;
# Location of our static files
root /path/to/dir/myApp/public;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
# If you don't find the filename in the static files
# Then request it from the unicorn server
if (!-f $request_filename) {
proxy_pass http://unicorn_server;
break;
}
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /path/to/dir/myApp/public;
}
}
$ sudo /etc/init.d/nginx restart
Unicorn 起動
$ bundle exec unicorn_rails -c config/unicorn.rb -E development -D
Unicorn 停止
$ cat /tmp/unicorn.pid | xargs kill
# または
$ ps ax | grep unicorn | awk '{print $1}' | xargs kill
自動起動設定
$ sudo vim /etc/init.d/unicorn
設定内容は以下
#!/bin/sh
#chkconfig:2345 85 15
#description:unicorn shell
NAME="Unicorn"
ENV=development
ROOT_DIR="/home/vagrant/testapp"
#PID="${ROOT_DIR}/tmp/pids/unicorn.pid"
PID="/tmp/unicorn.pid"
CONF="${ROOT_DIR}/config/unicorn.rb"
OPTIONS=""
#OPTIONS="--path /rails_app"
start()
{
if [ -e $PID ]; then
echo "$NAME already started"
exit 1
fi
echo "start $NAME"
cd $ROOT_DIR
su - vagrant -c "cd ${ROOT_DIR} && bundle exec unicorn_rails -c ${CONF} -E ${ENV} -D ${OPTIONS}"
}
stop()
{
if [ ! -e $PID ]; then
echo "$NAME not started"
exit 1
fi
echo "stop $NAME"
kill -QUIT `cat ${PID}`
}
force_stop()
{
if [ ! -e $PID ]; then
echo "$NAME not started"
exit 1
fi
echo "stop $NAME"
kill -INT `cat ${PID}`
}
reload()
{
if [ ! -e $PID ]; then
echo "$NAME not started"
start
exit 0
fi
echo "reload $NAME"
kill -HUP `cat ${PID}`
}
restart()
{
stop
sleep 3
start
}
case "$1" in
start)
start
;;
stop)
stop
;;
force-stop)
force_stop
;;
reload)
reload
;;
restart)
restart
;;
*)
echo "Syntax Error: release [start|stop|force-stop|reload|restart]"
;;
esac
設定反映
$ sudo chmod 755 /etc/init.d/unicorn
$ sudo chkconfig unicorn on
既存の VirtualBox イメージから Box を作成する
この時は、いきなり、 vagrat が VM を認識しなくなったので、VirtualBoxを起動して
イメージ名を確認した。
下記コマンド、 [Virtual Box Image Name]
は その際に確認した名前を指定する
$ vagrant package --base [Virtual Box Image Name] --output [box_name].box
作成した Box ファイルから、別PCで VM を起動する
$ vagrant box add [image_name] [box_name].box
$ vagrant box list
$ vagrant init [image_name]
$ vagrant up
SSH Authentication Errorが発生して、vagrant up
が終わらない場合
以下コマンドにて、 autorized_keys
に追記する
$ curl https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub > .ssh/authorized_keys
参考
- rails + nginx + unicorn連携
- Vagrant(CentOS6.5)にRuby2.1.2 Rails4.1をインストール
- Vagrant(CentOS6.5)にRails4.1 + Nginx + Unicorn + MySQL環境でRailsを起動する。
- WindowsでVagrantの環境構築
- rails + nginx + unicorn連携
- Windows 7マシンで、VirtualBox+Vagrantを使いUbuntu 14.04を動かす
- windowsとvagrant間のファイル共有はsambaを使う
- vagrantにpingが通らなくてハマった話
使用ソフト License
- unicorn
- Rails Nginx 連携用
- GPLV2,V3
- Unicorn is licensed under (your choice) of the GPLv2 or later (GPLv3+ preferred), or Ruby (1.8)-specific terms. See the included LICENSE file for details.
- rails gem foreigner
- 外部制約キー導入用
- MIT
- Copyright (c) 2012 Matthew Higgins, released under the MIT License
- rails gem composite_primary_keys
- 複合主キー導入用
- MIT
- This code is free to use under the terms of the MIT licence.
- rails gem rb-readline bundle install error 対応