LoginSignup
13
16

More than 5 years have passed since last update.

Vagrant で CentOS + Rails + MySQL + Apache + SSL(オレオレ)の環境構築

Last updated at Posted at 2017-05-13

はじめに

本番環境に近い開発環境を構築してみたいと思い、環境構築した記録の備忘録です。

今回作成した開発環境の各々のversion
CentOS 7.2
Git 2.13.0
ruby 2.4.1
rails 5.1.1
apache 2.4.6
mysql 5.7

Vagrantの立ち上げ

vagrantとvirtualboxはインストール済みとして進めて行きますので、まだの方はインストールをお願いします。
ということで、vagrantのboxの追加から行なっていきます。

# boxの追加
$ vagrant box add centos72 https://github.com/CommanderK5/packer-centos-template/releases/download/0.7.2/vagrant-centos-7.2.box


# 作業ディレクトリの作成
$ mkdir ~/vagrant/sample
$ cd ~/vagrant/sample


# vagrantの初期設定
$ vagrant init centos72


# Vagrantfileの編集
$ vi Vagrantfile

26   config.vm.network "forwarded_port", guest: 80, host: 3000
27   config.vm.network "forwarded_port", guest: 443, host: 443

36   config.vm.network "private_network", ip: "192.168.33.10"
47   config.vm.synced_folder "./rails_app", "/home/vagrant/rails_app"

53   config.vm.provider "virtualbox" do |vb|
54   #   # Display the VirtualBox GUI when booting the machine
55   #   vb.gui = true
56   #
57   #   # Customize the amount of memory on the VM:
58     vb.memory = "1024"
59   end


# vagrantの起動
$ vagrant up

# vagrantにssh接続
$ vagrant ssh

vagrantに各種パッケージのインストール

# とりあえずのアップデート
$ sudo yum -y update

# Gitのためのパッケージ
$ sudo yum install -y curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-devel curl-devel

# rbenvのためのパッケージ
$ sudo yum install -y gcc bzip2 openssl-devel libyaml-devel libffi-devel readline-devel zlib-devel gdbm-devel ncurses-devel

# apacheのためのパッケージ
$ sudo yum install -y httpd-devel

Gitのインストール

最新版をインストールして行きます。
Karnel.orgまたはGithubで最新バージョンを「リンクのアドレスをコピー」してください。

# 古いversionのGitがあればアンインストール
$ sudo yum remove git

# 最新versionのGitをインストール
$ wget https://github.com/git/git/archive/v2.13.0.tar.gz
$ tar zxvf v2.13.0.tar.gz
$ cd git-2.13.0/
$ make prefix=/usr/local all
$ sudo make prefix=/usr/local install

# シェルの再起動
$ exec $SHELL -l

# Gitの確認
$ git --version

# 不要なファイルの削除
$ rm -rf v2.13.0.tar.gz
$ rm -rf git-2.13.0/

rubyのインストール

rubyに関しては、rbenvで管理していきます。
なので、rbenvのインストールから

# rbenvのインストール
$ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv

# ruby-buildのインストール(rbenv installに必要なため)
$ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build

# rbenvの設定を~/.bash_profileに記載
$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile

# ~/.bash_profileの再読み込み
$ source ~/.bash_profile

$ rbenv --version
rbenv 1.1.0-2-g4f8925a

rubyのインストール

# インストールできるrubyのversionのリストの表示
$ rbenv install -l

# version 2.4.1 をインストール(かなり時間がかかるので注意)
$ rbenv install 2.4.1
$ rbenv global 2.4.1
$ rbenv rehash

# rbenvの確認
$ rbenv versions
* 2.4.1 (set by /home/vagrant/.rbenv/version)

railsのインストール

$ gem update --system
$ gem install bundler --no-ri --no-rdoc
$ gem install rails --no-ri --no-rdoc

# railsの確認
$ rails -v
Rails 5.1.1

# railsプロジェクトの作成
$ cd ~/rails_app
$ rails new . -d mysql
$ sudo yum install -y mysql-devel

# Gemfileの編集
$ vi Gemfile

# 20行目のコメントアウトを外す
gem 'therubyracer', platforms: :ruby

$ bundle install

MySQLのインストール

mariaDBと競合するため、mariaDBを削除

# mariaDBの確認
$ rpm -qa | grep -i mariadb
mariadb-libs-5.5.44-2.el7.centos.x86_64

# mariaDBの削除
$ sudo yum -y remove mariadb-libs
$ rm -rf /var/lib/mysql/

MySQLのインストール

$ sudo yum localinstall http://dev.mysql.com/get/mysql57-community-release-el7-7.noarch.rpm

# mysql5.7以外をインストールしたい場合、この時点で
# /etc/yum.repos.d/mysql-community.repoのenabledを変更(使用したいバージョンの[enabled]を1に)

$ sudo yum -y install mysql-community-server

# MySQLの確認
$ mysqld --version
mysqld  Ver 5.7.18 for Linux on x86_64 (MySQL Community Server (GPL))

MySQLの設定

パスワードは「8文字以上、大文字の英字、小文字の英字、数字、記号」を全て入れないとダメなので注意!!!

# MySQLの起動
$ sudo systemctl start mysqld.service

# MySQLのrootのパスワードの確認
$ cat /var/log/mysqld.log | grep password
2017-05-13T07:37:14.286725Z 1 [Note] A temporary password is generated for root@localhost: ************

# MySQLの設定
$ mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root: ************

The existing password for the user account root has expired. Please set a new password.

New password: ********

Re-enter new password: ********
The 'validate_password' plugin is installed on the server.
The subsequent steps will run with the existing configuration
of the plugin.
Using existing password for root.

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

New password: ********

Re-enter new password: ********

Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
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! 

上記のコマンドで行なっているのは

  • rootユーザーのパスワード変更
  • 匿名(anonymous)ユーザーの削除
  • リモートホストからrootログイン禁止
  • テスト用データベース削除
  • ユーザー権限が保存されているテーブルをリロード
# 下記の設定を記載
$ sudo vi /etc/my.cnf

character-set-server = utf8
default_password_lifetime = 0

# MySQLの再起動
$ sudo systemctl restart mysqld.service

MySQL 5.7.11以降であれば default_password_lifetime は default で 0 らしいので必要ないかもしれません。

Apacheのインストール

今回のBoxには初めからインストールされてました。

# 一応インストールコマンドはこちら
$ sudo yum -y install httpd

# Apacheの確認
$ httpd -v
Server version: Apache/2.4.6 (CentOS)
Server built:   Apr 12 2017 21:03:28

Passengerのインストール

$ gem install passenger --no-ri --no-rdoc
$ rbenv rehash
$ passenger-install-apache2-module
実行結果の一部
--------------------------------------------
Almost there!

Please edit your Apache configuration file, and add these lines:

   LoadModule passenger_module /home/vagrant/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/passenger-5.1.4/buildout/apache2/mod_passenger.so
   <IfModule mod_passenger.c>
     PassengerRoot /home/vagrant/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/passenger-5.1.4
     PassengerDefaultRuby /home/vagrant/.rbenv/versions/2.4.1/bin/ruby
   </IfModule>

After you restart Apache, you are ready to deploy any number of web
applications on Apache, with a minimum amount of configuration!

Press ENTER when you are done editing.


--------------------------------------------

上記の文章を/etc/httpd/conf.d/passenger.confに設定
注:環境によって異なりますので各自出てきた文章をコピペしてください。

/etc/httpd/conf.d/passenger.conf
   LoadModule passenger_module /home/vagrant/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/passenger-5.1.4/buildout/apache2/mod_passenger.so
   <IfModule mod_passenger.c>
     PassengerRoot /home/vagrant/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/passenger-5.1.4
     PassengerDefaultRuby /home/vagrant/.rbenv/versions/2.4.1/bin/ruby
   </IfModule>

apacheの設定

/etc/httpd/conf.d/rails.conf
<VirtualHost *:80>

  ServerName localhost:80
  DocumentRoot /home/vagrant/rails_app/public
  RailsEnv development
  PassengerEnabled on
  ErrorLog /var/log/httpd/error_log
  CustomLog /var/log/httpd/access_log combined
  AddDefaultCharset UTF-8

  <Directory /home/vagrant/rails_app/public>
     AllowOverride all
     Require all granted
     Options -MultiViews
  </Directory>

</VirtualHost>
/etc/httpd/conf/httpd.conf
ServerName localhost:80
# httpd.confの文法チェック
$ apachectl configtest
Syntax OK

# Apacheの起動
$ sudo systemctl start httpd.service

このままだとPermission deniedのエラーが出るため

$ sudo chmod 755 /home/vagrant

一応これでHOST側からlocalhost:3000で接続すればrailsアプリケーションを見ることが可能です。

SSLの設定

$ sudo yum -y install mod_ssl openssl
$ cd /etc/pki/tls/certs

# 秘密鍵の作成
$ sudo make server.key

# 秘密鍵からパスフレーズを削除
$ sudo openssl rsa -in server.key -out server.key

# 証明書の作成
$ sudo make server.csr
umask 77 ; \
/usr/bin/openssl req -utf8 -new -key server.key -out server.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:JP
State or Province Name (full name) []:Osaka
Locality Name (eg, city) [Default City]:Osaka
Organization Name (eg, company) [Default Company Ltd]:Sample

Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:127.0.0.1

Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

# 有効期限が10年の自己署名証明書を作成
$ sudo openssl x509 -in server.csr -out server.crt -req -signkey server.key -days 3650

apacheの設定

$ sudo vi /etc/httpd/conf.d/rails.conf

#下記を追記

<VirtualHost *:443>
  ServerName localhost:443
  SSLEngine on
  SSLCertificateFile /etc/pki/tls/certs/server.crt
  SSLCertificateKeyFile /etc/pki/tls/certs/server.key
  DocumentRoot /home/vagrant/rails_app/public
  RailsEnv development
  PassengerEnabled on
  ErrorLog /var/log/httpd/ssl_error_log
  CustomLog /var/log/httpd/ssl_access_log combined
  AddDefaultCharset UTF-8

  <Directory /home/vagrant/rails_app/public>
  AllowOverride all
  Require all granted
  Options -MultiViews
  </Directory>
</VirtualHost>

# apacheの再起動
$ sudo service httpd restart

あとはHOST側からhttps://192.168.33.10でいけるはず。

最後に

ufwを用いてファイアーウォールの管理もしたいのですが、開発環境には必要ないのかも。
ufwに関しては今後勉強します。

あと、apache関連については知識不足ですので、よく理解しておりません。
勉強しておきます。

誰かのために役立てていただければ幸いです。

追記

2018/04/25

curl-develのインストールが必要になっていたため、追記しました。

13
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
16