たくろぐ!

世界一のチラ裏

Rails本番環境構築(CentOS7)

環境

  • CentOS7.8(さくらのVPS
  • Rails6.0.3.2
  • Ruby2.7.1
  • sqlite3(今後MySQLに変更予定)
  • Puma
  • Nginx(リバースプロキシ)

CentOS

# cat /etc/redhat-release 
CentOS Linux release 7.8.2003 (Core)

yum update

インストール:
  kernel.x86_64 0:3.10.0-1127.18.2.el7                                                               kernel-devel.x86_64 0:3.10.0-1127.18.2.el7                                                              
更新:
  bind-export-libs.x86_64 32:9.11.4-16.P2.el7_8.6   bind-libs.x86_64 32:9.11.4-16.P2.el7_8.6            bind-libs-lite.x86_64 32:9.11.4-16.P2.el7_8.6         bind-license.noarch 32:9.11.4-16.P2.el7_8.6  
  bind-utils.x86_64 32:9.11.4-16.P2.el7_8.6         bpftool.x86_64 0:3.10.0-1127.18.2.el7               ca-certificates.noarch 0:2020.2.41-70.0.el7_8         curl.x86_64 0:7.29.0-57.el7_8.1              
  dbus.x86_64 1:1.10.24-14.el7_8                    dbus-libs.x86_64 1:1.10.24-14.el7_8                 git.x86_64 0:1.8.3.1-23.el7_8                         grub2.x86_64 1:2.02-0.86.el7.centos          
  grub2-common.noarch 1:2.02-0.86.el7.centos        grub2-pc.x86_64 1:2.02-0.86.el7.centos              grub2-pc-modules.noarch 1:2.02-0.86.el7.centos        grub2-tools.x86_64 1:2.02-0.86.el7.centos    
  grub2-tools-extra.x86_64 1:2.02-0.86.el7.centos   grub2-tools-minimal.x86_64 1:2.02-0.86.el7.centos   kernel-headers.x86_64 0:3.10.0-1127.18.2.el7          kernel-tools.x86_64 0:3.10.0-1127.18.2.el7   
  kernel-tools-libs.x86_64 0:3.10.0-1127.18.2.el7   libcurl.x86_64 0:7.29.0-57.el7_8.1                  libsss_idmap.x86_64 0:1.16.4-37.el7_8.4               libsss_nss_idmap.x86_64 0:1.16.4-37.el7_8.4  
  mokutil.x86_64 0:15-8.el7                         ntpdate.x86_64 0:4.2.6p5-29.el7.centos.2            perl-Git.noarch 0:1.8.3.1-23.el7_8                    python-perf.x86_64 0:3.10.0-1127.18.2.el7    
  rsyslog.x86_64 0:8.24.0-52.el7_8.2                selinux-policy.noarch 0:3.13.1-266.el7_8.1          selinux-policy-targeted.noarch 0:3.13.1-266.el7_8.1   sos.noarch 0:3.8-9.el7.centos                
  sssd-client.x86_64 0:1.16.4-37.el7_8.4            systemd.x86_64 0:219-73.el7_8.9                     systemd-libs.x86_64 0:219-73.el7_8.9                  systemd-python.x86_64 0:219-73.el7_8.9       
  systemd-sysv.x86_64 0:219-73.el7_8.9     

rbenv

# git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
Cloning into '/root/.rbenv'...
remote: Enumerating objects: 14, done.
remote: Counting objects: 100% (14/14), done.
remote: Compressing objects: 100% (13/13), done.
remote: Total 2861 (delta 3), reused 4 (delta 1), pack-reused 2847
Receiving objects: 100% (2861/2861), 553.04 KiB | 423.00 KiB/s, done.
Resolving deltas: 100% (1784/1784), done.

ruby-build

# git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
Cloning into '/root/.rbenv/plugins/ruby-build'...
remote: Enumerating objects: 52, done.
remote: Counting objects: 100% (52/52), done.
remote: Compressing objects: 100% (35/35), done.
remote: Total 11047 (delta 24), reused 32 (delta 13), pack-reused 10995
Receiving objects: 100% (11047/11047), 2.34 MiB | 1.87 MiB/s, done.
Resolving deltas: 100% (7282/7282), done.

パスを通す

# echo '# rbenv' >> ~/.bash_profile
# echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
# echo 'eval "$(rbenv init -)"' >> ~/.bash_profile

Ruby依存パッケージインストール

インストール:
  openssl-devel.x86_64 1:1.0.2k-19.el7                                  readline-devel.x86_64 0:6.2-11.el7                                  zlib-devel.x86_64 0:1.2.7-18.el7                                 
依存性関連をインストールしました:
  keyutils-libs-devel.x86_64 0:1.5.8-3.el7   krb5-devel.x86_64 0:1.15.1-46.el7     libcom_err-devel.x86_64 0:1.42.9-17.el7        libkadm5.x86_64 0:1.15.1-46.el7   libselinux-devel.x86_64 0:2.5-15.el7  
  libsepol-devel.x86_64 0:2.5-10.el7         libverto-devel.x86_64 0:0.2.5-4.el7   ncurses-devel.x86_64 0:5.9-14.20130511.el7_4   pcre-devel.x86_64 0:8.32-17.el7  

ruby

# rbenv install 2.7.1
Downloading ruby-2.7.1.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.7/ruby-2.7.1.tar.bz2
Installing ruby-2.7.1...
Installed ruby-2.7.1 to /root/.rbenv/versions/2.7.1

node.js

# webpack用
# curl -sL https://rpm.nodesource.com/setup_14.x | bash -
省略
# sudo yum install -y nodejs
インストール:
  nodejs.x86_64 2:14.7.0-1nodesource     

yarn

# webpack用
# npm install --global yarn
/usr/bin/yarn -> /usr/lib/node_modules/yarn/bin/yarn.js
/usr/bin/yarnpkg -> /usr/lib/node_modules/yarn/bin/yarn.js
+ yarn@1.22.4
added 1 package in 0.314s

Nginx(リバースプロキシ用)

インストール:
  nginx.x86_64 1:1.16.1-1.el7                                                                                                                                                                                 

依存性関連をインストールしました:
  dejavu-fonts-common.noarch 0:2.33-6.el7         dejavu-sans-fonts.noarch 0:2.33-6.el7                  fontconfig.x86_64 0:2.13.0-4.3.el7           fontpackages-filesystem.noarch 0:1.44-8.el7            
  gd.x86_64 0:2.0.35-26.el7                       gperftools-libs.x86_64 0:2.6.1-1.el7                   libX11.x86_64 0:1.6.7-2.el7                  libX11-common.noarch 0:1.6.7-2.el7                     
  libXau.x86_64 0:1.0.8-2.1.el7                   libXpm.x86_64 0:3.5.12-1.el7                           libjpeg-turbo.x86_64 0:1.2.90-8.el7          libxcb.x86_64 0:1.13-1.el7                             
  libxslt.x86_64 0:1.1.28-5.el7                   nginx-all-modules.noarch 1:1.16.1-1.el7                nginx-filesystem.noarch 1:1.16.1-1.el7       nginx-mod-http-image-filter.x86_64 1:1.16.1-1.el7      
  nginx-mod-http-perl.x86_64 1:1.16.1-1.el7       nginx-mod-http-xslt-filter.x86_64 1:1.16.1-1.el7       nginx-mod-mail.x86_64 1:1.16.1-1.el7         nginx-mod-stream.x86_64 1:1.16.1-1.el7                 

# sudo systemctl start nginx

アプリのファイル

/etc/nginx/conf.d/kisi.conf

# pumaとはUNIXドメインソケット接続で通信
upstream puma {
  server unix:///root/Project/kisi/tmp/sockets/puma.sock;
}

server {
  listen 80;
  server_name localhost;
  keepalive_timeout 30;
  root /root/Project/kisi;

  # basic認証
  auth_basic "Private Property";
  auth_basic_user_file /etc/nginx/.htpasswd;

  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log;
  location / {
    proxy_pass http://puma;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
  }

  location ~* \.(ico|css|gif|jpe?g|png|js|woff2|woff|ttf)(\?[0-9]+)?$ {
     expires max;
     break;
  }

  error_page 500 502 503 504 /500.html;
}

共通設定ファイル

/etc/nginx/nginx.conf

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user root;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

#    server {
#        listen       80 default_server;
#        listen       [::]:80 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#          proxy_pass http://127.0.0.1:3000;
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

production設定

シークレット

# bundle exec rails secret
文字列を控える  
  
# cat config/secrets.yml 
production:
  secret_key_base: 文字列を入力する

config/environments/production.rb

+  config.public_file_server.enabled = true
+  config.assets.compile = true

config/puma.rb

+# Change to match your CPU core count
+workers 2
+
+# Min and Max threads per worker
+threads 1, 6
+
+# Project folder
+app_dir = File.expand_path("../..", __FILE__)
+
+# Default to production
+rails_env = ENV.fetch("RAILS_ENV") { "production" }
+environment rails_env
+
+# Set up socket location
+#bind "unix://#{app_dir}/tmp/puma/puma.sock"
+bind "unix://#{Rails.root}/tmp/sockets/puma.sock"
+
+# Logs
+stdout_redirect "#{app_dir}/log/puma.stdout.log", "#{app_dir}/log/puma.stderr.log", true
+
+# Set master PID and state locations
+pidfile "#{app_dir}/tmp/puma/pid"
+state_path "#{app_dir}/tmp/puma/state"
+
+# Establish db connection for new processes
+on_worker_boot do
+  require "active_record"
+  ActiveSupport.on_load(:active_record) do
+    ActiveRecord::Base.establish_connection(YAML.load_file("#{app_dir}/config/database.yml")[rails_env])
+  end
+end

 # Allow puma to be restarted by `rails restart` command.
 plugin :tmp_restart
+
+# Puma control rack application
+activate_control_app

config/puma/production.rb

+# UNIX Domain Socket Settings
+app_root_path = "#{File.expand_path("../../..", __FILE__)}" # get application root path
+bind "unix://#{app_root_path}/tmp/sockets/puma.sock"

package-lock.json

省略

package.json

省略

yarn.lock

省略

メモ

Apachehttpd)をアンインストール

インストール

インストール:
  httpd.x86_64 0:2.4.6-93.el7.centos                                                                                                                                                                          
依存性関連をインストールしました:
  httpd-tools.x86_64 0:2.4.6-93.el7.centos    

アンインストール

削除しました:
  httpd.x86_64 0:2.4.6-93.el7.centos 

Apache依存パッケージ

インストール

インストール:
  httpd-devel.x86_64 0:2.4.6-93.el7.centos                                                                                                                                                                    
依存性関連をインストールしました:
  apr-devel.x86_64 0:1.4.8-5.el7         apr-util-devel.x86_64 0:1.5.2-6.el7         cyrus-sasl.x86_64 0:2.1.26-23.el7     cyrus-sasl-devel.x86_64 0:2.1.26-23.el7     expat-devel.x86_64 0:2.1.0-11.el7    
  libdb-devel.x86_64 0:5.3.21-25.el7     openldap-devel.x86_64 0:2.4.44-21.el7_6    

アンインストール

削除しました:
  apr-util-devel.x86_64 0:1.5.2-6.el7                                                                                                                                                                         
依存性の削除をしました:
  httpd-devel.x86_64 0:2.4.6-93.el7.centos     
削除しました:
  apr-devel.x86_64 0:1.4.8-5.el7 

残ったファイル

/var/log/httpd/access_log
/var/log/httpd/error_log
/etc/httpd/conf/httpd.conf.rpmsave # /etc/httpd/conf/httpd.confが保存されている  

さくらのVPSの設定

以下のパケットフィルタで80/443ポートを開放してあげる。
これないといくらサーバ起動しても403 Forbiddenされてアクセスできない。

manual.sakura.ad.jp

ちなみにSELinuxはデフォルトでOFFになってたから問題なかった。