MacPortsからHomebrewへの移行&環境構築(Ruby&Apache&MySQL)

2015/11/09 更新

f:id:hrt0kmt:20151107231633p:plain

環境


なぜHomebrewにしたか

  • 参考にしたサイトがほとんどと言っていいほどHomebrewを事前にインストールしている必要があった(特にRubyの自動化系)
  • 単純にHomebrewが使いたい


事前学習

brew tapについて

これは便利!Homebrewに追加されたtapコマンドはリポジトリを追加して簡単にフォーミュラを増やせる

brew tapは不要な場合が多い


事前準備とHomebrewのインストール

MacPortsのアンインストール

% sudo port -fp uninstall --follow-dependents installed

% sudo rm -rf /opt/local


環境変数コメントアウト

# MacPorts
#export PATH=/opt/local/bin:/opt/local/sbin:$PATH
# Apache
#export PATH=/opt/local/apache2/bin:/opt/local/bin:/opt/local/sbin:$PATH
#export MANPATH=/opt/local/share/man:$MANPATH
# MySQL
#export PATH=/opt/local/lib/mysql56/bin:$PATH
# PEAR
#export PATH=/opt/local/lib/php/pear:$PATH
#export PATH=/opt/local/share/pear:$PATH
# Ant
#export ANT_HOME="/opt/local/bin/ant"


Xcodeのインストール

Xcodeをインストール後、Command Line Toolsをインストール。

% xcode-select --install


本家ページにあるインストール用curlコマンドを打つ。

% ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
==> This script will install:
/usr/local/bin/brew
/usr/local/Library/...

brew doctorを走らせて診断。

% brew doctor
Your system is ready to brew.


wgetのインストール

% brew install wget
==> Installing dependencies for wget: openssl
==> Installing wget dependency: openssl
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl/certs

and run
  /usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include


OpenSSLの最適化

// デフォルトのバージョン
% openssl version
OpenSSL 0.9.8zg 14 July 2015

// HomebrewのOpenSSLへリンク
% brew link openssl --force
Linking /usr/local/Cellar/openssl/1.0.2d_1... 1548 symlinks created

% which openssl
/usr/local/bin/openssl

% openssl version
OpenSSL 1.0.2d 9 Jul 2015


Rubyの環境構築

rbenvのセットアップ

% brew update

% brew install rbenv ruby-build
To use Homebrew's directories rather than ~/.rbenv add to your profile:
  export RBENV_ROOT=/usr/local/var/rbenv

To enable shims and autocompletion add to your profile:
  if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi


インストールしたrbenvの環境変数の設定

環境設定ファイルに以下を追加。

# rbenv
export RBENV_ROOT=/usr/local/var/rbenv
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

Root直下に直接インストールしたくない場合は、下記のようにユーザー配下にインストールする。

hrt0kmt.hatenablog.com


Rubyのインストール

インストールできるバージョンを確認し、インストール。

% rbenv install -l

% rbenv install 2.2.3
Installed ruby-2.2.3 to /usr/local/var/rbenv/versions/2.2.3

% rbenv rehash

% rbenv global 2.2.3

% which ruby
/usr/local/var/rbenv/shims/ruby

% ruby -v
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin15]


MySQLのインストール

% brew install mysql
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.

To connect:
    mysql -uroot

To have launchd start mysql at login:
  ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
Then to load mysql now:
  launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
Or, if you don't want/need launchctl, you can just run:
  mysql.server start


MySQLのサーバーを起動

注意: サーバーをスタートさせる際に権限の変更確認をとられる、ここで権限を変更しないと、 ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) とエラーが表示され何もできない。つまり、インストール直後はサーバーを起動させてから設定を色々と行えば良い。

% mysql.server start
Starting MySQL
.. SUCCESS!


MySQLへログインをこころみる

% mysql -uroot

入れなかった場合は、こちらの記事が参考になりました。


rootユーザの初期パスワードを生成

% /usr/local/opt/mysql/bin/mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root:

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No: y

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1
Using existing password for root.

Estimated strength of the password: 50
Change the password for root ? ((Press y|Y for Yes, any other key for No) : n

 ... skipping.
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.

All done!


自動でMySQLが立ち上がるよう設定

% ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
/Users/hrt0kmt/Library/LaunchAgents/homebrew.mxcl.mysql.plist -> /usr/local/opt/mysql/homebrew.mxcl.mysql.plist

% launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist


Powのインストール

% gem install powder

% rbenv rehash

% powder install
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  9039  100  9039    0     0   7172      0  0:00:01  0:00:01 --:--:--  7173


bundlerのインストール

% gem install bundler
Fetching: bundler-1.10.6.gem (100%)
Successfully installed bundler-1.10.6

% rbenv rehash

nokogiriのインストールでエラーが以下のように出てしまう場合は、% xcode-select --installよりCommand Line Toolsをインストールしておく。

Fetching: nokogiri-1.6.6.2.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing rails:
    ERROR: Failed to build gem native extension.

    /usr/local/var/rbenv/versions/2.2.3/bin/ruby -r ./siteconf20151108-71548-m66ptw.rb extconf.rb
checking if the C compiler accepts ... yes
checking if the C compiler accepts -Wno-error=unused-command-line-argument-hard-error-in-future... no
Building nokogiri using packaged libraries.
-----
The file "/usr/include/iconv.h" is missing in your build environment,
which means you haven't installed Xcode Command Line Tools properly.

To install Command Line Tools, try running `xcode-select --install` on
terminal and follow the instructions.  If it fails, open Xcode.app,
select from the menu "Xcode" - "Open Developer Tool" - "More Developer
Tools" to open the developer site, download the installer for your OS
version and run it.
-----
*** 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.

Gemfileから各Gemをインストール

% cat << EOS >> Gemfile
heredoc> source "http://rubygems.org"
heredoc> gem "rails"
heredoc> gem "selenium-webdriver"
heredoc> gem "capybara"
heredoc> gem "rspec"
heredoc> gem "pry-byebug"
heredoc> gem "phantomjs"
heredoc> gem "poltergeist"
heredoc> gem "database_cleaner"
heredoc> gem "factory_girl_rails"
heredoc> gem "shoulda-matchers"
heredoc> gem 'pry-rails'  # rails console(もしくは、rails c)でirbの代わりにpryを使われる
heredoc> gem 'pry-doc'    # methodを表示
heredoc> gem 'pry-byebug' # デバッグを実施(Ruby 2.0以降で動作する)
heredoc> gem 'pry-stack_explorer' # スタックをたどれる
heredoc> EOS

% bundle install


その他関連記事

hrt0kmt.hatenablog.com


パス構成

% rbenv versions
  system
* 2.2.3 (set by /usr/local/var/rbenv/version)

% which ruby
/usr/local/var/rbenv/shims/ruby

% which gem
/usr/local/var/rbenv/shims/gem


Apacheのインストール

% brew tap homebrew/dupes

% brew tap homebrew/apache

% brew search httpd24
homebrew/apache/httpd24

% brew install httpd24
==> Downloading https://homebrew.bintray.com/bottles/apr-1.5.2.el_capitan.bottle.tar.gz
######################################################################## 100.0%
==> Pouring apr-1.5.2.el_capitan.bottle.tar.gz
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local.

Apple's CLT package contains apr.
This formula is keg-only, which means it was not symlinked into /usr/local.

OS X already provides this software and installing another version in
parallel can cause all kinds of trouble.

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/zlib/lib
    CPPFLAGS: -I/usr/local/opt/zlib/include

To have launchd start homebrew/apache/httpd24 at login:
  ln -sfv /usr/local/opt/httpd24/*.plist ~/Library/LaunchAgents
Then to load homebrew/apache/httpd24 now:
  launchctl load ~/Library/LaunchAgents/homebrew.mxcl.httpd24.plist


シンボリックリンクの作成とplistのロード

%  ln -sfv /usr/local/opt/httpd24/*.plist ~/Library/LaunchAgents
/Users/hrt0kmt/Library/LaunchAgents/homebrew.mxcl.httpd24.plist -> /usr/local/opt/httpd24/homebrew.mxcl.httpd24.plist
%  launchctl load ~/Library/LaunchAgents/homebrew.mxcl.httpd24.plist


ターミナルを再起動。

% which apachectl
/usr/local/bin/apachectl

% apachectl -v
Server version: Apache/2.4.17 (Unix)
Server built:   Nov  9 2015 19:27:39

任意にhttpd.confhttpd-vhosts.confを編集。

% sudo vi /usr/local/etc/apache2/2.4/httpd.conf


Apacheのスタート

% sudo apachectl stop
httpd (no pid file) not running
% sudo apachectl start


エラーログは /usr/local/var/log/apache2/error_log配下に吐かれる。


PHP (56) のインストール

% brew tap homebrew/dupes

% brew tap homebrew/versions

% brew tap homebrew/homebrew-php

% brew search php

% brew install php56

==> Pouring gettext-0.19.6.el_capitan.bottle.tar.gz
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local.

OS X provides the BSD gettext library and some software gets confused if both are in the library path.

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/gettext/lib
    CPPFLAGS: -I/usr/local/opt/gettext/include

==> Pouring php56-5.6.15.el_capitan.bottle.3.tar.gz
==> Caveats
To enable PHP in Apache add the following to httpd.conf and restart Apache:
    LoadModule php5_module    /usr/local/opt/php56/libexec/apache2/libphp5.so

The php.ini file can be found in:
    /usr/local/etc/php/5.6/php.ini

✩✩✩✩ Extensions ✩✩✩✩

If you are having issues with custom extension compiling, ensure that
you are using the brew version, by placing /usr/local/bin before /usr/sbin in your PATH:

      PATH="/usr/local/bin:$PATH"

PHP56 Extensions will always be compiled against this PHP. Please install them
using --without-homebrew-php to enable compiling against system PHP.

✩✩✩✩ PHP CLI ✩✩✩✩

If you wish to swap the PHP you use on the command line, you should add the following to ~/.bashrc,
~/.zshrc, ~/.profile or your shell's equivalent configuration file:

      export PATH="$(brew --prefix homebrew/php/php56)/bin:$PATH"

✩✩✩✩ FPM ✩✩✩✩

To launch php-fpm on startup:
    mkdir -p ~/Library/LaunchAgents
    cp /usr/local/opt/php56/homebrew.mxcl.php56.plist ~/Library/LaunchAgents/
    launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.php56.plist

The control script is located at /usr/local/opt/php56/sbin/php56-fpm

OS X 10.8 and newer come with php-fpm pre-installed, to ensure you are using the brew version you need to make sure /usr/local/sbin is before /usr/sbin in your PATH:

  PATH="/usr/local/sbin:$PATH"

You may also need to edit the plist to use the correct "UserName".

Please note that the plist was called 'homebrew-php.josegonzalez.php56.plist' in old versions
of this formula.

To have launchd start homebrew/php/php56 at login:
  ln -sfv /usr/local/opt/php56/*.plist ~/Library/LaunchAgents
Then to load homebrew/php/php56 now:
  launchctl load ~/Library/LaunchAgents/homebrew.mxcl.php56.plist


php.iniの設定

% vi /usr/local/etc/php/5.6/php.ini
date.timezone = Asia/Tokyo
mbstring.language = Japanese
mbstring.internal_encoding = UTF-8
mbstring.detect_order = UTF-8,SJIS,EUC-JP,JIS,ASCII
% brew install php56-apcu

To finish installing apcu for PHP 5.6:
  * /usr/local/etc/php/5.6/conf.d/ext-apcu.ini was created,
    do not forget to remove it upon extension removal.
  * Validate installation via one of the following methods:
  *
  * Using PHP from a webserver:
  * - Restart your webserver.
  * - Write a PHP page that calls "phpinfo();"
  * - Load it in a browser and look for the info on the apcu module.
  * - If you see it, you have been successful!
  *
  * Using PHP from the command line:
  * - Run "php -i" (command-line "phpinfo()")
  * - Look for the info on the apcu module.
  * - If you see it, you have been successful!

% brew install php56-xdebug

% brew install composer


参考サイト

https://github.com/sstephenson/rbenv/issues/508
http://tsuchikazu.net/mac_rail_setup/
https://gist.github.com/gaspanik/9284658
http://qiita.com/sxo/items/e19128309ce6d927448e
http://qiita.com/livejam_db/items/b70caccdeece036a3797