Redmine のサーバー（nginx + unicorn）起動方法


メール設定方法もあります。こちら（準備中）

初心者向きではないです。すみません。
結構メモ感あります。ちゃんと纏めます。

## 必要なもの
・Redmineのソースコード
・AWS EC2インスンタンス => 今度作り方説明できれば
・Capistrano => デプロイ用
・ローカルでRedmineが起動できること [Redmineローカル起動方法](http://qiita.com/issobero/items/4478e6ae9471b132af6e)

## Capistranoの設定

詳しい説明は別途
Gemfileに以下文言を追加。
今回は (Capistrano 2.15.5) を使う。

```Gemfile
# -------------------------------
# AWS & app server
# -------------------------------
gem 'unicorn'
gem 'unicorn-worker-killer'
gem 'aws-sdk'
gem 'aws-s3'
gem 'dalli'

# -------------------------------
# capistrano
# -------------------------------
group :development do
  gem 'capistrano', '~> 2.15.5'
  gem 'capistrano_colors'
  gem 'capistrano-rails'
  gem "capistrano-unicorn", '~> 0.1.10', require: false
  gem 'capistrano-rbenv'
  gem 'capistrano-maintenance'
  gem 'capistrano-ext'
  gem "debugger"
  gem 'spring'
end
```

```Gemfile
bundle exec capify .
# => これが出ればOK
# [add] writing './Capfile'
# [add] writing './config/deploy.rb'
# [done] capified!
```

## Gitの設定

```git
# gitが必要なので、Gitの整備をしますーー；
# Git Labにてプロジェクト設定 # Git Labの構築方法は希望があれば・・・
git init

```

git add . の前に ignore の設定変更


```.gitignore
# -------------------------------
# 無視リスト
# -------------------------------
*.tmp_*
.*
# Gemfile.lock
log/*.log
public/files/*
public/system/*
public/javascripts/translations.js
tmp/
vendor/bundle
db/schema.rb
dump.sql
lib/plugins/*
# -------------------------------
# ホワイトリスト
# -------------------------------
!.gitignore
```

```gitコマンド
git add .
git commit -m 'first commit'
git remote add [Gitのホスト] 
cinq_redmine.git
git push -u origin master
```

ということでデプロイします。

```capコマンド
bundle exec cap deploy:setup
# => 勝手にセットアップしてくれるので待ちます。
bundle exec cap deploy
# => 多分すぐ終わります♪
```

## サーバーの準備

```ubuntsuコマンド
adduser redmine
# => redmine用 ユーザーを作成します。
sudo gpasswd -a redmine sudo
# => sudo権限を与える
su - redmine
# => redmine ユーザーへへm校
ssh-keygen -t rsa
# => keyを作成
chown redmine:redmine *
# => 筆者は別のユーザーからキーをコピーするんでコピー後ユーザー変更
mysql -u root -p
GRANT ALL PRIVILEGES ON *.* TO redmine@localhost IDENTIFIED BY 'redmine' WITH GRANT OPTION;
# => MYSQLのユーザー作成
GRANT ALL PRIVILEGES ON *.* TO redmine@'%' IDENTIFIED BY 'redmine' WITH GRANT OPTION;
# => MYSQLのユーザー作成 外部から操作可能にする。
bundle install
bundle exec rake db:create RAILS_ENV=production
# => Database作成
bundle exec rake db:migrate RAILS_ENV=production
# => Database table 作成
bundle exec rake redmine:load_default_data RAILS_ENV=production
# => データフロー作成
bundle exec rails s -e production
```

アクセスしてみます。
http:://ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com:3000
=> 無事出来ました。
unicron.rbの中身を以下の通り設定

```config/unicron.rb
#------------------------------------------------------------------------------
# 起動確認 コマンド
# bundle exec unicorn_rails -E production -c config/unicorn.rb
#------------------------------------------------------------------------------
WORKING_DIR = "/home/redmine/rails/current"

worker_processes 4
working_directory "#{WORKING_DIR}"

# listen on both a Unix domain socket and a TCP port,
# we use a shorter backlog for quicker failover when busy
listen "#{WORKING_DIR}/tmp/sockets/unicorn.sock", :backlog => 2048
listen 8081, :tcp_nopush => true

# nuke workers after 30 seconds instead of 60 seconds (the default)
timeout 60 # タイムアウトは１分

# feel free to point this anywhere accessible on the filesystem
pid "tmp/pids/unicorn.pid"

# By default, the Unicorn logger will write to stderr.
# Additionally, ome applications/frameworks log to stderr or stdout,
# so prevent them from going to /dev/null when daemonized here:
stderr_path "log/unicorn.stderr.log"
stdout_path "log/unicorn.stdout.log"

# combine Ruby 2.0.0dev or REE with "preload_app true" for memory savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
  GC.copy_on_write_friendly = true

# Enable this flag to have unicorn test client connections by writing the
# beginning of the HTTP headers before calling the application.  This
# prevents calling the application for connections that have disconnected
# while queued.  This is only guaranteed to detect clients on the same
# host unicorn runs on, and unlikely to detect disconnects even on a
# fast LAN.
check_client_connection false

=begin
before_fork do |server, worker|
  # the following is highly recomended for Rails + "preload_app true"
  # as there's no need for the master process to hold a connection
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.connection.disconnect!

  if Rails.application.config.session_store #<= ActionDispatch::Session::MemCacheStore
    Rails.logger.info "##UNICORN WILL FORK## pid=#{$$}"
    ObjectSpace.each_object(ActionDispatch::Session::MemCacheStore) do |obj|
      Rails.logger.info "##RESET MEMCACHED CONNECTION## pid=#{$$}"
      obj.instance_variable_get(:@pool).reset
    end
  end
end
=end

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|
  #GC.disable
  # the following is *required* for Rails + "preload_app true",
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.establish_connection
  defined?(MultiDb) and
    MultiDb::ConnectionProxy.setup!

  # if preload_app is true, then you may also want to check and
  # restart any other shared sockets/descriptors such as Memcached,
  # and Redis.  TokyoCabinet file handles are safe to reuse
  # between any number of forked children (assuming your kernel
  # correctly implements pread()/pwrite() system calls)
end

# GC関連の設定
class Unicorn::HttpServer
  module MyOobGc
    def process_client(client)
      GC.disable
      super(client)
      #t1 = Time.now
      GC.enable
      GC.start
      #Rails.logger.info "MY OOBGC #{Time.now - t1} sec"
    end
  end
  prepend MyOobGc
end
```

ここで重要なのは「WORKING_DIR」とポート番号です。
WORKING_DIR => デプロイ先とする。
ポート番号    => 使っていないポートにして下さい.tomcatとか上げていると8080は専有されています。

```unicronモードでの起動
bundle exec unicorn_rails -E production -c config/unicorn.rb -D
```

http://ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com:8081/
=> アクセスできれば成功

アクセスできたんでサーバーを殺します。

```
ps -ef | grep unicorn_rails 

#---結果---
redmine  31053     1  4 17:26 ?        00:00:03 unicorn_rails master -E production -c config/unicorn.rb -D
redmine  31057 31053  0 17:26 ?        00:00:00 unicorn_rails worker[0] -E production -c config/unicorn.rb -D
redmine  31060 31053  0 17:26 ?        00:00:00 unicorn_rails worker[1] -E production -c config/unicorn.rb -D
redmine  31063 31053  0 17:26 ?        00:00:00 unicorn_rails worker[2] -E production -c config/unicorn.rb -D
redmine  31066 31053  0 17:26 ?        00:00:00 unicorn_rails worker[3] -E production -c config/unicorn.rb -D
redmine  31075 30856  0 17:28 pts/2    00:00:00 grep --color=auto unicorn_rails
#------

# => マスターを殺せばいいので
kill -p 31053
ps -ef | grep unicorn_rails 

```

## nginx関連

nginxをインストールされていることが大前提

configを設定します。

```sites-available/redmine
upstream redmine {
    server 127.0.0.1:8081;
}
server {
    listen 80 default_server;
    server_name [ドメイン名];
    root /home/redmine/rails/current/public;

#    location /users {
#      auth_basic "admin?";
#      auth_basic_user_file /etc/nginx/.htpasswd;
#    }

#    location ~ ^/assets/?(.+)$ {
#      include /etc/nginx/X-App-Server.conf;
#      root /home/cinqing/rails/current/app;
#      gzip_static on;
#      expires max;
#      add_header Cache-Control public;
#      try_files /assets/images/$1 /assets/javascripts/$1 /assets/stylesheets/$1 /404.html =404;
#    }

    location / {
#        include /etc/nginx/X-App-Server.conf;
        try_files $uri $uri/index.html $uri.html @rails;
#      auth_basic "admin?";
#      auth_basic_user_file /etc/nginx/.htpasswd;
    }

    location @rails {
#        include /etc/nginx/X-App-Server.conf;
        proxy_redirect     off;
        proxy_set_header   X-FORWARDED_PROTO $http_x_forwarded_proto;
        proxy_set_header   Host              $http_host;
        proxy_set_header   X-Real-IP         $http_x_forwarded_for;
        proxy_set_header   X-Forwarded-For   $http_x_forwarded_for;
        proxy_pass http://redmine;
        proxy_intercept_errors on;
        error_page 404 /404.html;
        error_page 422 /422.html;
        error_page 500 502 503 504 /500.html;
    }

}
```

上記で設定したconfigファイルが間違っていないか確認します。

```
ln -s /etc/nginx/sites-available/redmine redmine
nginx -t -c /etc/nginx/nginx.conf
# =>
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
/etc/init.d/nginx restart
# => nginxを再起動します。
```