ubuntu 12.04LTSへredmine+nginx+unicornでインストール

Ubuntu 12.04LTSで稼働中のnginxとunicornにredmineをセットアップします。

githubからclone

root@IPD-0197:/home# cd /var
root@IPD-0197:/var# git clone https://github.com/redmine/redmine.git
Cloning into 'redmine'...
remote: Counting objects: 123923, done.
remote: Compressing objects: 100% (434/434), done.
remote: Total 123923 (delta 245), reused 0 (delta 0), pack-reused 123481
Receiving objects: 100% (123923/123923), 41.71 MiB | 3.42 MiB/s, done.
Resolving deltas: 100% (94044/94044), done.
Checking connectivity... done.
root@IPD-0197:/var# cd redmine/
root@IPD-0197:/var/redmine# ls
app  config     CONTRIBUTING.md  doc    files    lib  plugins  Rakefile     script  tmp
bin  config.ru  db               extra  Gemfile  log  public   README.rdoc  test
root@IPD-0197:/var/redmine#

最新のstableブランチに切り替える

root@IPD-0197:/var/redmine# git branch -a
* master
  remotes/origin/0.6-stable
  remotes/origin/0.7-stable
  remotes/origin/0.8-stable
  remotes/origin/0.9-stable
  remotes/origin/1.0-stable
  remotes/origin/1.1-stable
  remotes/origin/1.2-stable
  remotes/origin/1.3-stable
  remotes/origin/1.4-stable
  remotes/origin/2.0-stable
  remotes/origin/2.1-stable
  remotes/origin/2.2-stable
  remotes/origin/2.3-stable
  remotes/origin/2.4-stable
  remotes/origin/2.5-stable
  remotes/origin/2.6-stable
  remotes/origin/3.0-stable
  remotes/origin/3.1-stable
  remotes/origin/HEAD -> origin/master
  remotes/origin/integration-to-svn-stable-1.0
  remotes/origin/integration-to-svn-trunk
  remotes/origin/master
  remotes/origin/nbc
  remotes/origin/plugin-hooks
  remotes/origin/swistak
  remotes/origin/work
root@IPD-0197:/var/redmine# git checkout -b 3.1-stable remotes/origin/3.1-stable
Branch 3.1-stable set up to track remote branch 3.1-stable from origin.
Switched to a new branch '3.1-stable'
root@IPD-0197:/var/redmine# git branch
* 3.1-stable
  master
root@IPD-0197:/var/redmine#

mysqlにredmine用のデータベースとユーザーを作成します。(passwordは独自に設定)

root@IPD-0197:/var/redmine# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 64
Server version: 5.5.44-0ubuntu0.12.04.1 (Ubuntu)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database redmine character set utf8;
Query OK, 1 row affected (0.00 sec)

mysql> create user 'redmine'@'localhost' identified by '**********';
Query OK, 0 rows affected (0.00 sec)

mysql> grant all privileges on redmine.* to 'redmine'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye
root@IPD-0197:/var/redmine#

データベースのコンフィグレーション

root@IPD-0197:/var/redmine# ls config
additional_environment.rb.example  boot.rb                    database.yml.example  environments  locales    settings.yml
application.rb                     configuration.yml.example  environment.rb        initializers  routes.rb
root@IPD-0197:/var/redmine# cp config/database.yml{.example,}
root@IPD-0197:/var/redmine# ls config
additional_environment.rb.example  boot.rb                    database.yml          environment.rb  initializers  routes.rb
application.rb                     configuration.yml.example  database.yml.example  environments    locales       settings.yml

root@IPD-0197:/var/redmine# vi config/database.yml
# Default setup is given for MySQL with ruby1.9.
# Examples for PostgreSQL, SQLite3 and SQL Server can be found at the end.
# Line indentation must be 2 spaces (no tabs).

production:
  adapter: mysql2
  database: redmine
  host: localhost
  username: redmine   <== 変更
  password: "**********" <== 変更
  encoding: utf8

development:
  adapter: mysql2
  database: redmine_development
  host: localhost
  username: root
  password: ""
  encoding: utf8

  (以下省略)

セッションストア秘密鍵を生成する

root@IPD-0197:/var/redmine# rake generate_secret_token
Could not find gem 'rails (= 4.2.4) ruby' in the gems available on this machine.
Run `bundle install` to install missing gems.

なんかエラーになった。
指示通りに”bundle install”やってみる。

root@IPD-0197:/var/redmine# bundle install
Don't run Bundler as root. Bundler can ask for sudo if it is needed, and installing your bundle as root will break this application for all
non-root users on this machine.
Fetching gem metadata from https://rubygems.org/.........
Resolving dependencies...
Installing rake 10.4.2
Installing i18n 0.7.0
Installing json 1.8.3
Installing minitest 5.8.1
Installing thread_safe 0.3.5
Installing tzinfo 1.2.2
Installing activesupport 4.2.4
Installing builder 3.2.2
Installing erubis 2.7.0
Installing mini_portile 0.6.2
Installing nokogiri 1.6.6.2
Installing rails-deprecated_sanitizer 1.0.3
Installing rails-dom-testing 1.0.7
Installing loofah 2.0.3
Installing rails-html-sanitizer 1.0.2
Installing actionview 4.2.4
Installing rack 1.6.4
Installing rack-test 0.6.3
Installing actionpack 4.2.4
Installing globalid 0.3.6
Installing activejob 4.2.4
Installing mime-types 2.6.2
Installing mail 2.6.3
Installing actionmailer 4.2.4
Installing actionpack-action_caching 1.1.1
Installing actionpack-xml_parser 1.0.2
Installing activemodel 4.2.4
Installing arel 6.0.3
Installing activerecord 4.2.4
Using bundler 1.6.2
Installing xpath 2.0.0
Installing capybara 2.5.0
Installing ffi 1.9.10
Installing childprocess 0.5.6
Installing coderay 1.1.0
Installing docile 1.1.5
Installing thor 0.19.1
Installing railties 4.2.4
Installing jquery-rails 3.1.4
Installing metaclass 0.0.4
Installing mocha 1.1.0
Installing multi_json 1.11.2
Installing mysql2 0.3.20
Installing net-ldap 0.3.1
Installing protected_attributes 1.1.3
Installing ruby-openid 2.3.0
Installing rack-openid 1.4.2
Installing sprockets 3.4.0
Installing sprockets-rails 2.3.3
Installing rails 4.2.4
Installing rbpdf 1.18.6
Installing rdoc 4.2.0
Installing redcarpet 3.3.3
Installing request_store 1.0.5

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

    /usr/local/bin/ruby extconf.rb
checking for gcc... yes
checking for Magick-config... no
checking for pkg-config... yes
Package MagickCore was not found in the pkg-config search path.
Perhaps you should add the directory containing `MagickCore.pc'
to the PKG_CONFIG_PATH environment variable
No package 'MagickCore' found
checking for outdated ImageMagick version (<= 6.4.9)... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/usr/local/bin/ruby

Gem files will remain installed in /usr/local/lib/ruby/gems/2.0.0/gems/rmagick-2.15.4 for inspection.
Results logged to /usr/local/lib/ruby/gems/2.0.0/gems/rmagick-2.15.4/ext/RMagick/gem_make.out
An error occurred while installing rmagick (2.15.4), and Bundler cannot continue.
Make sure that `gem install rmagick -v '2.15.4'` succeeds before bundling.
root@IPD-0197:/var/redmine#

またまた、失敗した。

http://d.hatena.ne.jp/kitokitoki/20130714/p3

Ubuntu13.04 で gem install rmagick -v ’2.13.2′ に失敗したときの対処例 – わからん
のページを参照。

root@IPD-0197:/var/redmine# apt-get install imagemagick libmagickwand-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
imagemagick is already the newest version.
The following packages were automatically installed and are no longer required:
  git-man liberror-perl libjpeg62
Use 'apt-get autoremove' to remove them.
The following NEW packages will be installed:
  libmagickwand-dev
0 upgraded, 1 newly installed, 0 to remove and 3 not upgraded.
Need to get 449 kB of archives.
After this operation, 2,538 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
Get:1 http://jp.archive.ubuntu.com/ubuntu/ precise-updates/main libmagickwand-dev amd64 8:6.6.9.7-5ubuntu3.3 [449 kB]
Fetched 449 kB in 0s (2,173 kB/s)
Selecting previously unselected package libmagickwand-dev.
(Reading database ... 111593 files and directories currently installed.)
Unpacking libmagickwand-dev (from .../libmagickwand-dev_8%3a6.6.9.7-5ubuntu3.3_amd64.deb) ...
Processing triggers for man-db ...
Setting up libmagickwand-dev (8:6.6.9.7-5ubuntu3.3) ...
root@IPD-0197:/var/redmine#
root@IPD-0197:/var/redmine# gem install rmagick -v '2.15.4'
Building native extensions.  This could take a while...
Successfully installed rmagick-2.15.4
Parsing documentation for rmagick-2.15.4
Installing ri documentation for rmagick-2.15.4
Done installing documentation for rmagick after 11 seconds
1 gem installed

再度チャレンジしてみると、成功

root@IPD-0197:/var/redmine# bundle install
Don't run Bundler as root. Bundler can ask for sudo if it is needed, and installing your bundle as root will break this application for all
non-root users on this machine.
Fetching gem metadata from https://rubygems.org/.........
Resolving dependencies...
Using rake 10.4.2
Using i18n 0.7.0
Using json 1.8.3
Using minitest 5.8.1
Using thread_safe 0.3.5
Using tzinfo 1.2.2
Using activesupport 4.2.4
Using builder 3.2.2
Using erubis 2.7.0
Using mini_portile 0.6.2
Using nokogiri 1.6.6.2
Using rails-deprecated_sanitizer 1.0.3
Using rails-dom-testing 1.0.7
Using loofah 2.0.3
Using rails-html-sanitizer 1.0.2
Using actionview 4.2.4
Using rack 1.6.4
Using rack-test 0.6.3
Using actionpack 4.2.4
Using globalid 0.3.6
Using activejob 4.2.4
Using mime-types 2.6.2
Using mail 2.6.3
Using actionmailer 4.2.4
Using actionpack-action_caching 1.1.1
Using actionpack-xml_parser 1.0.2
Using activemodel 4.2.4
Using arel 6.0.3
Using activerecord 4.2.4
Using bundler 1.6.2
Using xpath 2.0.0
Using capybara 2.5.0
Using ffi 1.9.10
Installing childprocess 0.5.7
Using coderay 1.1.0
Using docile 1.1.5
Using thor 0.19.1
Using railties 4.2.4
Using jquery-rails 3.1.4
Using metaclass 0.0.4
Using mocha 1.1.0
Using multi_json 1.11.2
Using mysql2 0.3.20
Using net-ldap 0.3.1
Using protected_attributes 1.1.3
Using ruby-openid 2.3.0
Using rack-openid 1.4.2
Using sprockets 3.4.0
Using sprockets-rails 2.3.3
Using rails 4.2.4
Using rbpdf 1.18.6
Using rdoc 4.2.0
Using redcarpet 3.3.3
Using request_store 1.0.5
Using rmagick 2.15.4
Installing rubyzip 1.1.7
Installing websocket 1.2.2
Installing selenium-webdriver 2.48.1
Installing simplecov-html 0.9.0
Installing simplecov 0.9.2
Installing yard 0.8.7.6
Your bundle is complete!
Use `bundle show [gemname]` to see where a bundled gem is installed.
root@IPD-0197:/var/redmine#

やっとできる

root@IPD-0197:/var/redmine# rake generate_secret_token
root@IPD-0197:/var/redmine#

データベース上にテーブルを作成

Redmineのインストールディレクトリで下記コマンドを実行します。

root@IPD-0197:/var/redmine# RAILS_ENV=production rake db:migrate
== 1 Setup: migrating =========================================================
-- create_table("attachments", {:force=>true})
   -> 0.0904s
-- create_table("auth_sources", {:force=>true})
   -> 0.0919s
-- create_table("custom_fields", {:force=>true})
   -> 0.0932s
-- create_table("custom_fields_projects", {:id=>false, :force=>true})
   -> 0.0920s
-- create_table("custom_fields_trackers", {:id=>false, :force=>true})
   -> 0.0920s
-- create_table("custom_values", {:force=>true})
   -> 0.0920s
-- create_table("documents", {:force=>true})
   -> 0.0920s
-- add_index("documents", ["project_id"], {:name=>"documents_project_id"})
   -> 0.1758s

 (中略)

== 20150525103953 ClearEstimatedHoursOnParentIssues: migrating ================
== 20150525103953 ClearEstimatedHoursOnParentIssues: migrated (0.0023s) =======

== 20150526183158 AddRolesTimeEntriesVisibility: migrating ====================
-- add_column(:roles, :time_entries_visibility, :string, {:limit=>30, :default=>"all", :null=>false})
   -> 0.3009s
== 20150526183158 AddRolesTimeEntriesVisibility: migrated (0.3010s) ===========

== 20150528084820 AddRolesAllRolesManaged: migrating ==========================
-- add_column(:roles, :all_roles_managed, :boolean, {:default=>true, :null=>false})
   -> 0.5031s
== 20150528084820 AddRolesAllRolesManaged: migrated (0.5033s) =================

== 20150528092912 CreateRolesManagedRoles: migrating ==========================
-- create_table(:roles_managed_roles, {:id=>false})
   -> 0.2423s
== 20150528092912 CreateRolesManagedRoles: migrated (0.2424s) =================

== 20150528093249 AddUniqueIndexOnRolesManagedRoles: migrating ================
-- add_index(:roles_managed_roles, [:role_id, :managed_role_id], {:unique=>true})
   -> 0.1922s
== 20150528093249 AddUniqueIndexOnRolesManagedRoles: migrated (0.1924s) =======

root@IPD-0197:/var/redmine#

デフォルトデータをデータベースに登録

root@IPD-0197:/var/redmine# RAILS_ENV=production rake redmine:load_default_data

Select language: ar, az, bg, bs, ca, cs, da, de, el, en, en-GB, es, es-PA, et, eu, fa, fi, fr, gl, he, hr, hu, id, it, ja, ko, lt, lv, mk, mn, nl, no, pl, pt, pt-BR, ro, ru, sk, sl, sq, sr, sr-YU, sv, th, tr, uk, vi, zh, zh-TW [en] ja
====================================
Default configuration data loaded.
root@IPD-0197:/var/redmine#

webrick で起動テスト

redmineとMySQLのインストールが問題なくできているかを確認する為にwebrickという
Ruby簡易HTTPサーバを利用してRedmineの起動テストを実施する。

root@IPD-0197:/var/redmine# ruby bin/rails server webrick -e production
=> Booting WEBrick
=> Rails 4.2.4 application starting in production on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2015-10-25 22:44:26] INFO  WEBrick 1.3.1
[2015-10-25 22:44:26] INFO  ruby 2.0.0 (2013-11-22) [x86_64-linux]
[2015-10-25 22:44:26] INFO  WEBrick::HTTPServer#start: pid=25718 port=3000

Webブラウザでアクセスしてみる。

http://localhost:3000

確認できたら、[CTRL]+Cで終了する。

^C[2015-10-25 22:45:12] INFO  going to shutdown ...
[2015-10-25 22:45:12] INFO  WEBrick::HTTPServer#start done.
Exiting

Redmineディレクトリー権限を変更

root@IPD-0197:/var/redmine# chown -R www-data:www-data files/ log/ tmp/ public/plugin_assets/
root@IPD-0197:/var/redmine# chmod -R 755 files/ log/ tmp/ public/plugin_assets/
root@IPD-0197:/var/redmine# ll
total 112
drwxr-xr-x 17 root     root     4096 Oct 25 16:06 ./
drwxr-xr-x 17 root     root     4096 Oct 25 16:00 ../
drwxr-xr-x  6 root     root     4096 Oct 23 01:01 app/
drwxr-xr-x  2 root     root     4096 Oct 23 01:01 bin/
drwxr-xr-x  5 root     root     4096 Oct 23 01:22 config/
-rw-r--r--  1 root     root      160 Oct 23 01:01 config.ru
-rw-r--r--  1 root     root      241 Oct 23 01:01 CONTRIBUTING.md
drwxr-xr-x  3 root     root     4096 Oct 25 16:11 db/
drwxr-xr-x  2 root     root     4096 Oct 23 01:11 doc/
drwxr-xr-x  5 root     root     4096 Oct 23 01:01 extra/
drwxr-xr-x  2 www-data www-data 4096 Oct 23 01:01 files/
-rw-r--r--  1 root     root     3475 Oct 23 01:11 Gemfile
-rw-r--r--  1 root     root     4298 Oct 25 16:06 Gemfile.lock
drwxr-xr-x  8 root     root     4096 Oct 23 01:11 .git/
-rw-r--r--  1 root     root      739 Oct 23 01:01 .gitignore
-rw-r--r--  1 root     root      615 Oct 23 01:01 .hgignore
drwxr-xr-x  7 root     root     4096 Oct 23 01:11 lib/
drwxr-xr-x  2 www-data www-data 4096 Oct 25 16:09 log/
drwxr-xr-x  2 root     root     4096 Oct 23 01:01 plugins/
drwxr-xr-x  8 root     root     4096 Oct 23 01:01 public/
-rw-r--r--  1 root     root      275 Oct 23 01:01 Rakefile
-rw-r--r--  1 root     root      205 Oct 23 01:01 README.rdoc
drwxr-xr-x  2 root     root     4096 Oct 23 01:01 script/
drwxr-xr-x 11 root     root     4096 Oct 23 01:11 test/
drwxr-xr-x  9 www-data www-data 4096 Oct 25 16:20 tmp/
-rw-r--r--  1 root     root     6631 Oct 23 01:11 .travis.yml

Unicornのインストールと設定

root@IPD-0197:/var/redmine# echo "gem 'unicorn'" >> Gemfile.local
root@IPD-0197:/var/redmine# bundle install
Don't run Bundler as root. Bundler can ask for sudo if it is needed, and installing your bundle as root will break this application for all
non-root users on this machine.
Fetching gem metadata from https://rubygems.org/.........
Resolving dependencies...
Using rake 10.4.2
Using i18n 0.7.0
Using json 1.8.3
Using minitest 5.8.1
Using thread_safe 0.3.5
Using tzinfo 1.2.2
Using activesupport 4.2.4
Using builder 3.2.2
Using erubis 2.7.0
Using mini_portile 0.6.2
Using nokogiri 1.6.6.2
Using rails-deprecated_sanitizer 1.0.3
Using rails-dom-testing 1.0.7
Using loofah 2.0.3
Using rails-html-sanitizer 1.0.2
Using actionview 4.2.4
Using rack 1.6.4
Using rack-test 0.6.3
Using actionpack 4.2.4
Using globalid 0.3.6
Using activejob 4.2.4
Using mime-types 2.6.2
Using mail 2.6.3
Using actionmailer 4.2.4
Using actionpack-action_caching 1.1.1
Using actionpack-xml_parser 1.0.2
Using activemodel 4.2.4
Using arel 6.0.3
Using activerecord 4.2.4
Using bundler 1.6.2
Using xpath 2.0.0
Using capybara 2.5.0
Using ffi 1.9.10
Using childprocess 0.5.7
Using coderay 1.1.0
Using docile 1.1.5
Using thor 0.19.1
Using railties 4.2.4
Using jquery-rails 3.1.4
Installing kgio 2.10.0
Using metaclass 0.0.4
Using mocha 1.1.0
Using multi_json 1.11.2
Using mysql2 0.3.20
Using net-ldap 0.3.1
Using protected_attributes 1.1.3
Using ruby-openid 2.3.0
Using rack-openid 1.4.2
Using sprockets 3.4.0
Using sprockets-rails 2.3.3
Using rails 4.2.4
Installing raindrops 0.15.0
Using rbpdf 1.18.6
Using rdoc 4.2.0
Using redcarpet 3.3.3
Using request_store 1.0.5
Using rmagick 2.15.4
Using rubyzip 1.1.7
Using websocket 1.2.2
Using selenium-webdriver 2.48.1
Using simplecov-html 0.9.0
Using simplecov 0.9.2
Installing unicorn 4.9.0
Using yard 0.8.7.6
Your bundle is complete!
Use `bundle show [gemname]` to see where a bundled gem is installed.
root@IPD-0197:/var/redmine#

インストールされたようだ。
サンプルファイルのありかを探して、redmineインストールディレクトリーにコピーする。

root@IPD-0197:/# find . -name "unicorn.conf*"
./usr/local/lib/ruby/gems/2.0.0/gems/unicorn-4.9.0/examples/unicorn.conf.minimal.rb
./usr/local/lib/ruby/gems/2.0.0/gems/unicorn-4.9.0/examples/unicorn.conf.rb
./home/git/gitlab/vendor/bundle/ruby/2.0.0/gems/unicorn-4.6.3/examples/unicorn.conf.minimal.rb
./home/git/gitlab/vendor/bundle/ruby/2.0.0/gems/unicorn-4.6.3/examples/unicorn.conf.rb
root@IPD-0197:/#
root@IPD-0197:/# cp /usr/local/lib/ruby/gems/2.0.0/gems/unicorn-4.9.0/examples/unicorn.conf.rb /var/redmine/config/unicorn.rb

編集する

# Sample verbose configuration file for Unicorn (not Rack)
#
# This configuration file documents many features of Unicorn
# that may not be needed for some applications. See
# http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb
# for a much simpler configuration file.
#
# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete
# documentation.

# Use at least one worker per core if you're on a dedicated server,
# more will usually help for _short_ waits on databases/caches.
worker_processes 4

# Since Unicorn is never exposed to outside clients, it does not need to
# run on the standard HTTP port (80), there is no reason to start Unicorn
# as root unless it's from system init scripts.
# If running the master process as root and the workers as an unprivileged
# user, do this to switch euid/egid in the workers (also chowns logs):
# user "unprivileged_user", "unprivileged_group"
user "www-data", "www-data"  <strong><span style="color: #ff0000;">追加</span></strong>

# Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up.
#working_directory "/path/to/app/current" # available in 0.94.0+ <strong><span style="color: #ff0000;">コメントアウト</span></strong>
working_directory "/var/redmine" # available in 0.94.0+ <strong><span style="color: #ff0000;">追加</span></strong>

# listen on both a Unix domain socket and a TCP port,
# we use a shorter backlog for quicker failover when busy
#listen "/path/to/.unicorn.sock", :backlog => 64 <strong><span style="color: #ff0000;">コメントアウト</span></strong>
#listen 8080, :tcp_nopush => true  <strong><span style="color: #ff0000;">コメントアウト</span></strong>
listen "/tmp/redmine.sock", :backlog => 64   <strong><span style="color: #ff0000;">追加</span></strong>

# nuke workers after 30 seconds instead of 60 seconds (the default)
#timeout 30  <strong><span style="color: #ff0000;">コメントアウト</span></strong>

# feel free to point this anywhere accessible on the filesystem
#pid "/path/to/app/shared/pids/unicorn.pid"  <strong><span style="color: #ff0000;">コメントアウト</span></strong>
pid File.expand_path('tmp/pids/unicorn.pid', ENV['RAILS_ROOT'])  <strong><span style="color: #ff0000;">追加</span></strong>

# 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 "/path/to/app/shared/log/unicorn.stderr.log"  <strong><span style="color: #ff0000;">コメントアウト</span></strong>
#stdout_path "/path/to/app/shared/log/unicorn.stdout.log"  <strong><span style="color: #ff0000;">コメントアウト</span></strong>
stderr_path File.expand_path('log/unicorn.stderr.log', ENV['RAILS_ROOT']) <strong><span style="color: #ff0000;">追加</span></strong>
stdout_path File.expand_path('log/unicorn.stdout.log', ENV['RAILS_ROOT']) <strong><span style="color: #ff0000;">追加</span></strong>

# 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

# local variable to guard against running a hook multiple times
run_once = true

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!

  # Occasionally, it may be necessary to run non-idempotent code in the
  # master before forking.  Keep in mind the above disconnect! example
  # is idempotent and does not need a guard.
  if run_once
    # do_something_once_here ...
    run_once = false # prevent from firing again
  end

  # The following is only recommended for memory/DB-constrained
  # installations.  It is not needed if your system can house
  # twice as many worker_processes as you have configured.
  #
  # # This allows a new master process to incrementally
  # # phase out the old master process with SIGTTOU to avoid a
  # # thundering herd (especially in the "preload_app false" case)
  # # when doing a transparent upgrade.  The last worker spawned
  # # will then kill off the old master process with a SIGQUIT.
   old_pid = "#{server.config[:pid]}.oldbin"     <strong><span style="color: #ff0000;">有効化</span></strong>
   if old_pid != server.pid               <strong><span style="color: #ff0000;">有効化</span></strong>
     begin                         <strong><span style="color: #ff0000;">有効化</span></strong>
       sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU  <strong><span style="color: #ff0000;">有効化</span></strong>
       Process.kill(sig, File.read(old_pid).to_i)   <strong><span style="color: #ff0000;">有効化</span></strong>
     rescue Errno::ENOENT, Errno::ESRCH         <strong><span style="color: #ff0000;">有効化</span></strong>
     end                          <strong><span style="color: #ff0000;">有効化</span></strong>
   end                            <strong><span style="color: #ff0000;">有効化</span></strong>
  #
  # Throttle the master from forking too quickly by sleeping.  Due
  # to the implementation of standard Unix signal handlers, this
  # helps (but does not completely) prevent identical, repeated signals
  # from being lost when the receiving process is busy.
   sleep 1
end

after_fork do |server, worker|
  # per-process listener ports for debugging/admin/migrations
  # addr = "127.0.0.1:#{9293 + worker.nr}"
  # server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true)

  # the following is *required* for Rails + "preload_app true",
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.establish_connection

  # 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

動作確認する。

root@IPD-0197:/var/redmine# bundle exec unicorn_rails -c config/unicorn.rb -E production -D
root@IPD-0197:/var/redmine# ps axu | grep unicorn
git       1809  0.0  1.7 516996 139408 ?       Sl   Oct13   0:16 unicorn_rails master -D -c /home/git/gitlab/config/unicorn.rb -E production
git       2197  0.0  1.7 521380 137836 ?       Sl   Oct13   0:09 unicorn_rails worker[0] -D -c /home/git/gitlab/config/unicorn.rb -E production
git       2201  0.0  1.7 526736 141992 ?       Sl   Oct13   0:09 unicorn_rails worker[1] -D -c /home/git/gitlab/config/unicorn.rb -E production
root     26364  7.3  1.3 333848 110276 ?       Sl   23:32   0:02 unicorn_rails master -c config/unicorn.rb -E production -D
www-data 26368  0.0  1.3 333848 106804 ?       Sl   23:32   0:00 unicorn_rails worker[0] -c config/unicorn.rb -E production -D
www-data 26371  0.0  1.3 333848 106824 ?       Sl   23:32   0:00 unicorn_rails worker[1] -c config/unicorn.rb -E production -D
www-data 26374  0.0  1.3 333848 106652 ?       Sl   23:32   0:00 unicorn_rails worker[2] -c config/unicorn.rb -E production -D
www-data 26377  0.0  1.3 333980 106880 ?       Sl   23:32   0:00 unicorn_rails worker[3] -c config/unicorn.rb -E production -D
root     26384  0.0  0.0   9388   940 pts/0    S+   23:32   0:00 grep --color=auto unicorn
root@IPD-0197:/var/redmine# kill -KILL 26364
root@IPD-0197:/var/redmine# ps axu | grep unicorn
git       1809  0.0  1.7 516996 139408 ?       Sl   Oct13   0:16 unicorn_rails master -D -c /home/git/gitlab/config/unicorn.rb -E production
git       2197  0.0  1.7 521380 137836 ?       Sl   Oct13   0:09 unicorn_rails worker[0] -D -c /home/git/gitlab/config/unicorn.rb -E production
git       2201  0.0  1.7 526736 141992 ?       Sl   Oct13   0:09 unicorn_rails worker[1] -D -c /home/git/gitlab/config/unicorn.rb -E production
root     26386  0.0  0.0   9384   940 pts/0    S+   23:35   0:00 grep --color=auto unicorn

Redmineの起動スクリプト

root@IPD-0197:/var/redmine# vi /etc/init.d/unicorn
#!/bin/sh

### BEGIN INIT INFO
# Provides:          unicorn
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start unicorn for redmine at boot time
# Description:       The Unicorn for redmine
### END INIT INFO
# <span style="color: #ff0000;">bundlerのバージョンはインストールされたものに合わせる</span>
export PATH="${PATH:+$PATH:}/usr/local/lib/ruby/gems/2.0.0/gems/bundler-1.6.2/bin:/usr/local/bin"
#PATH=/bin:/usr/bin:/sbin:/usr/sbin

# move to project root directory
NAME=unicorn
ENVIROMENT=production

# SCRIPT_DIR=`dirname $0`
# ROOT_DIR=$(cd "${SCRIPT_DIR}/../../"; pwd)
ROOT_DIR="/var/redmine"

PID="${ROOT_DIR}/tmp/pids/unicorn.pid"
CONF="${ROOT_DIR}/config/unicorn.rb"
BUNDLE_BIN="/usr/local/bin/bundle"

start()
{
  if [ -e $PID ]; then
    echo "$NAME already started";
    exit 1;
  fi
  echo "start $NAME";
  cd $ROOT_DIR
  bundle exec unicorn_rails -c ${CONF} -E ${ENVIROMENT} -D
}

stop()
{
  if [ ! -e $PID ]; then
    echo "$NAME not started";
    exit 1;
  fi
  echo "stop $NAME";
  kill -QUIT `cat ${PID}`
  rm -f $PID
}

force_stop()
{
  if [ ! -e $PID ]; then
    echo "$NAME not started";
    exit 1;
  fi
  echo "stop $NAME";
  kill -TERM `cat ${PID}`
  rm -f $PID
}

reload()
{
  if [ ! -e $PID ]; then
    echo "$NAME not started";
    start
    exit 0;
  fi
  echo "reload $NAME";
  kill -HUP `cat ${PID}`
}

restart()
{
    stop
    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

root@IPD-0197:/var/redmine# chmod +x /etc/init.d/unicorn
root@IPD-0197:/var/redmine# sysv-rc-conf unicorn on
root@IPD-0197:/var/redmine# sysv-rc-conf --list | grep unicorn
unicorn      2:on       3:on    4:on    5:on
root@IPD-0197:/var/redmine#

システム停止・起動時の問題

root@IPD-0197:/var/redmine# sysv-rc-conf --list | grep unicorn
unicorn      2:on       3:on    4:on    5:on

システム停止時にちゃんと/etc/init.d/unicorn stopが呼ばれるように設定変更。

root@IPD-0197:/var/redmine# sysv-rc-conf --level 3 unicorn on
root@IPD-0197:/var/redmine# sysv-rc-conf --level 4 unicorn on
root@IPD-0197:/var/redmine# sysv-rc-conf --level 5 unicorn on
root@IPD-0197:/var/redmine# sysv-rc-conf --level 1 unicorn off
root@IPD-0197:/var/redmine# sysv-rc-conf --level 6 unicorn off

Redmineをサブディレクトリーで動作させる

root@IPD-0197:/var/redmine# vi config/environment.rb
# Load the rails application
require File.expand_path('../application', __FILE__)

# Make sure there's no plugin in vendor/plugin before starting
vendor_plugins_dir = File.join(Rails.root, "vendor", "plugins")
if Dir.glob(File.join(vendor_plugins_dir, "*")).any?
  $stderr.puts "Plugins in vendor/plugins (#{vendor_plugins_dir}) are no longer allowed. " +
    "Please, put your Redmine plugins in the `plugins` directory at the root of your " +
    "Redmine directory (#{File.join(Rails.root, "plugins")})"
  exit 1
end

# Initialize the rails application
RedmineApp::Application.initialize!

ActionController::Base.relative_url_root = "/redmine"   <=== 追加

root@IPD-0197:/var/redmine# vi config
config/    config.ru
root@IPD-0197:/var/redmine# vi config.ru
# This file is used by Rack-based servers to start the application.

require ::File.expand_path('../config/environment',  __FILE__)
#run RedmineApp::Application      <strong><span style="color: #ff0000;"><== コメントアウト</span></strong>
map ActionController::Base.relative_url_root || "/" do          <strong><span style="color: #ff0000;"><== 以降追加。</span></strong>
  run RedmineApp::Application
end

root@IPD-0197:/var/redmine#

nginxのconfを設定する

# Maintainer: @randx

# CHUNKED TRANSFER
# It is a known issue that Git-over-HTTP requires chunked transfer encoding [0] which is not
# supported by Nginx < 1.3.9 [1]. As a result, pushing a large object with Git (i.e. a single large file)
# can lead to a 411 error. In theory you can get around this by tweaking this configuration file and either
# - installing an old version of Nginx with the chunkin module [2] compiled in, or
# - using a newer version of Nginx.
#
# At the time of writing we do not know if either of these theoretical solutions works. As a workaround
# users can use Git over SSH to push large files.
#
# [0] https://git.kernel.org/cgit/git/git.git/tree/Documentation/technical/http-protocol.txt#n99
# [1] https://github.com/agentzh/chunkin-nginx-module#status
# [2] https://github.com/agentzh/chunkin-nginx-module

# this can be any application server, not just Unicorn/Rainbows!
upstream unicorn_redmine {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).

  # for UNIX domain socket setups:
  # server unix:/tmp/.sock fail_timeout=0;
  server unix:/tmp/redmine.sock fail_timeout=0;

  # for TCP setups, point these to your backend servers
  # server 192.168.0.7:8080 fail_timeout=0;
  # server 192.168.0.8:8080 fail_timeout=0;
  # server 192.168.0.9:8080 fail_timeout=0;
}

server {
  listen 443 ssl;        # e.g., listen 192.168.1.1:80; In most cases *:80 is a good idea
  server_name xxxx.xxxx.co.jp;     # e.g., server_name source.example.com;
  server_tokens off;     # don't show the version number, a security best practice
  root /var/www/public;
  
  # Increase this if you want to upload large attachments
  # Or if you want to accept large git objects over http
  client_max_body_size 20m;

  # individual nginx logs for this gitlab vhost
  access_log  /var/log/nginx/access.log;
  error_log   /var/log/nginx/error.log;

  ssl  on;
  ssl_certificate      /etc/nginx/certs/host.crt;
  ssl_certificate_key  /etc/nginx/certs/host.key;
  ssl_protocols SSLv3 TLSv1 TLSv1.2;
  ssl_ciphers AES:HIGH:!ADH:!MD5; 
  ssl_prefer_server_ciphers on;

  location ^~ /redmine {
    root /var/redmine/public;
    try_files $uri/index.html $uri.html $uri @redmine;
  }

  location @redmine {
    proxy_set_header   X-Real-IP         $remote_addr;
    proxy_set_header   X-Forwarded-Proto $scheme;
    # an HTTP header important enough to have its own Wikipedia entry:
    # http://en.wikipedia.org/wiki/X-Forwarded-For
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;

    # enable this if you forward HTTPS traffic to unicorn,
    # this helps Rack set the proper URL scheme for doing redirects:
    # proxy_set_header X-Forwarded-Proto $scheme;

    # pass the Host: header from the client right along so redirects
    # can be set properly within the Rack application
    proxy_set_header   Host $http_host;

    # we don't want nginx trying to do something clever with
    # redirects, we set the Host: header above already.
    proxy_redirect off;

    # set "proxy_buffering off" *only* for Rainbows! when doing
    # Comet/long-poll/streaming. It's also safe to set if you're using
    # only serving fast clients with Unicorn + nginx, but not slow
    # clients. You normally want nginx to buffer responses to slow
    # clients, even with Rails 3.1 streaming because otherwise a slow
    # client can become a bottleneck of Unicorn.
    #
    # The Rack application may also set "X-Accel-Buffering (yes|no)"
    # in the response headers do disable/enable buffering on a
    # per-response basis.
    # proxy_buffering off;

    proxy_pass http://unicorn_redmine;

  }
  error_page 502 /502.html;
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>