0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Ubuntu 24.04.1 LTS】Rails7でPassenger+ApacheのWebサーバを立てる(https編)

Posted at

前回、同じ構成のhttp編を投稿したので、今回はhttps編を投稿します。
構築タイミングが違うため、Rubyが3.3.8に上がっています。

基本情報

IP: 192.168.10.10
Ubuntu 24.04.1 LTS
Ruby on Rails 7.1.5.1
Ruby 3.3.8
rbenv 1.3.2
Gem 3.6.3
MariaDB Ver 15.1
apache2 Apache/2.4.58 (Ubuntu)
Passenger 6.0.27

前提条件

Railsのdevelopment環境では実行できている環境とします。
SSL証明書は別途用意してあることとします。
LAN内でのみ使用するサーバのため、http://IPアドレス で接続しています。

production環境準備

本番環境のプロジェクトを/var/www以下に配置

$ sudo cp -r ~/myrailspath/myproject/ /var/www/myproject/
$ sudo chown -R myusername:myusername /var/www/myproject/

DB環境準備

production環境のDBがない場合は作成しておく。(割愛)
database.ymlにパスワードを記載、migrate。

$ cd /var/www/myproject/
$ sudo vi config/database.yml
    # production:のパスワードを正しく記載

$ rails db:migrate RAILS_ENV=production
	# 各テーブル、VIEWが作られる

コンパイル

$ cd /var/www/myproject/
$ bundle exec rake assets:precompile RAILS_ENV=production

Apacheのセットアップ

Apacheのインストール

$ sudo apt update
$ sudo apt install apache2
$ apachectl -v
Server version: Apache/2.4.58 (Ubuntu)
Server built:   2025-08-11T11:10:09

$ sudo systemctl start apache2

SSLモジュールを有効化

$ sudo a2enmod ssl
$ sudo systemctl restart apache2

Passengerの導入

参考URL:https://blog.redmine.jp/articles/6_0/install/ubuntu24/
Redmineのインストール方法を元にしました

参考URLを元に必要なパッケージのインストール

$ apt list --installed | grep xxx

より各パッケージを調べてないものを入れる。私の場合はlibffi-dev、apache2-devでした。

$ sudo apt update
$ sudo apt install -y libffi-dev apache2-dev

Passengerのインストール

$ cd /var/www/myproject/
$ vi Gemfile
Gemfile
gem "passenger", "~> 6.0", ">= 6.0.27"
$ bundle install

PassengerのApache用モジュールのインストール

インストールコマンドのpathを調べる

$ which passenger-install-apache2-module
/home/myusername/.rbenv/shims/passenger-install-apache2-module

モジュールのインストール

$ sudo /home/myusername/.rbenv/shims/passenger-install-apache2-module --auto --languages ruby
# ・・・長々と実行のログがでて・・・
Detected 0 error(s), 1 warning(s).

Apache用設定内容の確認

$ passenger-install-apache2-module --snippet
LoadModule passenger_module /home/myusername/.rbenv/versions/3.3.8/lib/ruby/gems/3.3.0/gems/passenger-6.0.27/buildout/apache2/mod_passenger.so
<IfModule mod_passenger.c>
	PassengerRoot /home/myusername/.rbenv/versions/3.3.8/lib/ruby/gems/3.3.0/gems/passenger-6.0.27
	PassengerDefaultRuby /home/myusername/.rbenv/versions/3.3.8/bin/ruby
</IfModule>

この結果をconfに記載するため覚えておく

環境変数RAILS_MASTER_KEYの設定

keyの値を確認

$ cd /var/www/myproject/
$ less config/master.key
**************(keyの内容)
$ export RAILS_MASTER_KEY="**************(keyの内容)"

永続化する

echo 'RAILS_MASTER_KEY="**************(keyの内容)"' | sudo tee -a /etc/environment

ApacheのSSL設定

default-ssl.confをmy-ssl.confにコピー

$ sudo cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/my-ssl.conf
$ sudo vi /etc/apache2/sites-available/my-ssl.conf

1-6行目の内容は、先ほどの"passenger-install-apache2-module --snippet"の実行結果をそのまま記載する。
また証明書と秘密鍵の情報を記載します。

my-ssl.conf(抜粋)
# Passenger
LoadModule passenger_module /home/myusername/.rbenv/versions/3.3.8/lib/ruby/gems/3.3.0/gems/passenger-6.0.27/buildout/apache2/mod_passenger.so
<IfModule mod_passenger.c>
	PassengerRoot /home/myusername/.rbenv/versions/3.3.8/lib/ruby/gems/3.3.0/gems/passenger-6.0.27
	PassengerDefaultRuby /home/myusername/.rbenv/versions/3.3.8/bin/ruby
</IfModule>	

PassengerUserSwitching off
PassengerDefaultUser myusername
<VirtualHost *:443>
	# 変更または追記
		:
	DocumentRoot /var/www/myproject/public/
	<Directory /var/www/myproject/public/>
		AllowOverride all
		Require all granted
		Options -MultiViews
	</Directory>
	
	PassengerEnabled on
	PassengerAppRoot /var/www/myproject
	
	SSLCertificateFile /path/to/crtfile		#Webサーバ証明書ファイルパス 例:/etc/apache2/ssl/myserver.crt
	SSLCertificateKeyFile /path/to/keyfile	#Webサーバ証明書秘密鍵 例:/etc/apache2/ssl/myserver.key
	SSLCACertificateFile /path/to/cacrtfile	#認証局証明書※必要な場合 例:/etc/apache2/ssl/ca.crt
		:
</VirtualHost>

※ここでは編集部分のみ抜粋したものを載せていますが、下の方にファイル全体を記載しています。

000-default.confを無効化し、my-sslを適用させる(sites-enabledにリンクを作成する)

$ sudo a2dissite 000-default.conf
$ sudo a2ensite my-ssl.conf

有効なconfの確認

$ ls -la /etc/apache2/sites-enabled
lrwxrwxrwx 1 root root   30 Aug 19 15:39 my-ssl.conf -> ../sites-available/my-ssl.conf

confテスト

$ apache2ctl configtest
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
Syntax OK

passenger-statusが実行できるようにする

$ cd /home/myusername/.rbenv/shims/
$ sudo ./passenger-status
/home/myusername/.rbenv/versions/3.3.7/lib/ruby/gems/3.3.0/gems/passenger-6.0.27/src/ruby_supportlib/phusion_passenger/admin_tools/instance.rb:94:in `initialize': too long unix socket path (116bytes given but 108bytes max) (ArgumentError)
	sock = Net::BufferedIO.new(UNIXSocket.new("#{@path}/#{socket_path}"))

参考URL:https://qiita.com/kensukeyoshida/items/94727adb8581e57930bd
こちらの方と同様にPassengerInstanceRegistryDir /tmpもPASSENGER_TMPDIR=/tmp passenger-statusもうまくいかず、同じように下記

$ sudo systemctl edit apache2
[Service]
PrivateTmp=false

名前を以下の名前で保存。(デフォルトの名前だと保存されなかった)
/etc/systemd/system/apache2.service.d/override.conf

$ sudo systemctl daemon-reload

httpsで接続する場合はRailsの本番環境用の設定ファイルproduction.rbでsslをtrueにしておく

$ vi /var/www/myproject/config/environments/production.rb
production.rb
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true

ファイアウォールの設定

$ sudo ufw allow 80/tcp
$ sudo ufw allow 443/tcp
$ sudo ufw reload
$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
443/tcp                    ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
443/tcp (v6)               ALLOW       Anywhere (v6)
80/tcp (v6)                ALLOW       Anywhere (v6)

動作確認

$ sudo systemctl restart apache2
$ sudo systemctl status apache2

ブラウザからアクセス。
https://192.168.10.10
開くはず!

my-ssl.conf全文

my-ssl.conf
# Passenger
LoadModule passenger_module /home/myusername/.rbenv/versions/3.3.8/lib/ruby/gems/3.3.0/gems/passenger-6.0.27/buildout/apache2/mod_passenger.so
<IfModule mod_passenger.c>
  PassengerRoot /home/myusername/.rbenv/versions/3.3.8/lib/ruby/gems/3.3.0/gems/passenger-6.0.27
  PassengerDefaultRuby /home/myusername/.rbenv/versions/3.3.8/bin/ruby
</IfModule>	

PassengerUserSwitching off
PassengerDefaultUser myusername

<VirtualHost *:443>
	ServerAdmin webmaster@localhost

	DocumentRoot /var/www/myproject/public/
	<Directory /var/www/myproject/public/>
		AllowOverride all
		Require all granted
		Options -MultiViews
	</Directory>

	PassengerEnabled on
	PassengerAppRoot /var/www/myproject

	# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
	# error, crit, alert, emerg.
	# It is also possible to configure the loglevel for particular
	# modules, e.g.
	#LogLevel info ssl:warn

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined

	# For most configuration files from conf-available/, which are
	# enabled or disabled at a global level, it is possible to
	# include a line for only one particular virtual host. For example the
	# following line enables the CGI configuration for this host only
	# after it has been globally disabled with "a2disconf".
	#Include conf-available/serve-cgi-bin.conf

	#   SSL Engine Switch:
	#   Enable/Disable SSL for this virtual host.
	SSLEngine on

	#   A self-signed (snakeoil) certificate can be created by installing
	#   the ssl-cert package. See
	#   /usr/share/doc/apache2/README.Debian.gz for more info.
	#   If both key and certificate are stored in the same file, only the
	#   SSLCertificateFile directive is needed.
	SSLCertificateFile	/etc/apache2/ssl/myproject.crt
	SSLCertificateKeyFile	/etc/apache2/ssl/myproject.key

	#   Server Certificate Chain:
	#   Point SSLCertificateChainFile at a file containing the
	#   concatenation of PEM encoded CA certificates which form the
	#   certificate chain for the server certificate. Alternatively
	#   the referenced file can be the same as SSLCertificateFile
	#   when the CA certificates are directly appended to the server
	#   certificate for convinience.
	#SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt

	#   Certificate Authority (CA):
	#   Set the CA certificate verification path where to find CA
	#   certificates for client authentication or alternatively one
	#   huge file containing all of them (file must be PEM encoded)
	#   Note: Inside SSLCACertificatePath you need hash symlinks
	#         to point to the certificate files. Use the provided
	#         Makefile to update the hash symlinks after changes.
	#SSLCACertificatePath /etc/ssl/certs/
	SSLCACertificateFile	/etc/apache2/ssl/ca.crt

	#   Certificate Revocation Lists (CRL):
	#   Set the CA revocation path where to find CA CRLs for client
	#   authentication or alternatively one huge file containing all
	#   of them (file must be PEM encoded)
	#   Note: Inside SSLCARevocationPath you need hash symlinks
	#         to point to the certificate files. Use the provided
	#         Makefile to update the hash symlinks after changes.
	#SSLCARevocationPath /etc/apache2/ssl.crl/
	#SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl

	#   Client Authentication (Type):
	#   Client certificate verification type and depth.  Types are
	#   none, optional, require and optional_no_ca.  Depth is a
	#   number which specifies how deeply to verify the certificate
	#   issuer chain before deciding the certificate is not valid.
	#SSLVerifyClient require
	#SSLVerifyDepth  10

	#   SSL Engine Options:
	#   Set various options for the SSL engine.
	#   o FakeBasicAuth:
	#    Translate the client X.509 into a Basic Authorisation.  This means that
	#    the standard Auth/DBMAuth methods can be used for access control.  The
	#    user name is the `one line' version of the client's X.509 certificate.
	#    Note that no password is obtained from the user. Every entry in the user
	#    file needs this password: `xxj31ZMTZzkVA'.
	#   o ExportCertData:
	#    This exports two additional environment variables: SSL_CLIENT_CERT and
	#    SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
	#    server (always existing) and the client (only existing when client
	#    authentication is used). This can be used to import the certificates
	#    into CGI scripts.
	#   o StdEnvVars:
	#    This exports the standard SSL/TLS related `SSL_*' environment variables.
	#    Per default this exportation is switched off for performance reasons,
	#    because the extraction step is an expensive operation and is usually
	#    useless for serving static content. So one usually enables the
	#    exportation for CGI and SSI requests only.
	#   o OptRenegotiate:
	#    This enables optimized SSL connection renegotiation handling when SSL
	#    directives are used in per-directory context.
	#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
	<FilesMatch "\.(?:cgi|shtml|phtml|php)$">
		SSLOptions +StdEnvVars
	</FilesMatch>
	<Directory /usr/lib/cgi-bin>
		SSLOptions +StdEnvVars
	</Directory>
</VirtualHost>

参考文献

本文中にも記載しましたが、下記URLを参考にさせていただきました。ありがとうございました。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?