U-Yuri’s 健忘録

U-Yuri’s 備忘録

プログラミングを勉強しています。アウトプットに活用しているブログです。

【Rails】Active Storageで投稿した画像が大きすぎるというエラー(nginx)

Railsでの設定か、nginxでの設定であるため、まずはnginxのエラーログを見る。

$ sudo less /var/log/nginx/error.log
#最新のログを見たいので、shift + g で最新のログへ

2024/04/25 22:42:43 [error] 2878351#2878351: *2304 client intended to send too large body: 1055110 bytes, client: 133.204.66.129, server: 〇〇.com, request: "POST /wants HTTP/1.1", host: "〇〇.com", referrer: "https://〇〇.com/wants/new"
~

too large body: 1055110 bytesというエラーがあるため、nginxの設定によるもの。
/etc/nginx/nginx.confのlocation内に以下を記述し20Mまで対応できるようにする。

server{
        server_name 〇〇.com;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        location / {
            proxy_pass http://127.0.0.1:3500;
            client_max_body_size 20M;
        }

$ sudo service nginx restartでnginxリスタート

これでOK。

【Rails】デプロイ-ドメイン当て-

$ sudo vim /etc/nginx/nginx.confでserver_nameを変更する。

server{
                server_name 〇〇.com; #ここにドメインを入れる。
                proxy_set_header X-Forwarded-Host $host;
                location / {
                        proxy_pass http://127.0.0.1:3500;
                }
        }

SSL化については以下の記事参考。 ⑤Railsアプリをデプロイするまで【SSL】【Let’s Encrypt】 - U-Yuri’s 備忘録

【Rails】サーバーの自動起動の設定

  1. /etc/systemd/system/〇〇.serviceファイルを作成する。※〇〇はなんでもいい(アプリの名前)。
[Unit]
Description=Mudazero App #アプリの説明
After=network.target #ネットワークの準備ができた後

[Service]
Type=simple
User=debian #自分のパソコンのuser
WorkingDirectory=/home/debian/mudamuda/ #アプリのダイレクトリー(pwdで調べる)
Environment=RAILS_ENV=production #本番環境で動く設定
ExecStart=/bin/bash -lc 'rails s' #bashはbashrc.のバッシュの設定(pathとはrbenv)を使用するため。サーバー起動のコマンド
Restart=on-failure #エラーあったらどうすれば良いかの設定

[Install]
WantedBy=multi-user.target #パソコンの起動が終わった後動かす。
  1. $ systemctl status mudazero.serviceで今の状態を確認
$ systemctl status mudazero.service
○ mudazero.service - Mudazero App
     Loaded: loaded (/etc/systemd/system/mudazero.service; disabled; preset: enabled)
     Active: inactive (dead)

#enable(有効)になってないという意味。

$ sudo systemctl enable mudazero.serviceでenable(有効)する。

$ systemctl status mudazero.serviceでもう一度確認する。

$ systemctl status mudazero.service
○ mudazero.service - Mudazero App
     Loaded: loaded (/etc/systemd/system/mudazero.service; enabled; preset: enabled)
     Active: inactive (dead)

service; enabled;になったがまだActive: inactive (dead)$ systemctl start mudazero.serviceでスタート。
$ systemctl restart mudazero.serviceでリスタート(設定を変更した後など))

'$ systemctl status mudazero.service'でlogや情報確認。
$ sudo journalctl -u mudazero.serviceでlogのみ確認できる。
$ sudo journalctl -u mudazero.service -fだと新しい情報のみなのでこっちの方が使いやすい。

これで完了。

【Rails】デプロイ①(サーバー内に複数アプリがある場合)

SSHでさくらVPSで繋げる

$ ssh debian@〇〇vs.sakura.ne.jp

rails側のcomfig/puma.rbを編集しポート番号変更。

#3000になっていたのを、3500に変更(3000は違うアプリで使用しているので)。
port ENV.fetch("PORT") { 3500 }

③上記変更をGithubにpush

$ sudo vim /etc/nginx/nginx.confを書き換える。

  server{
                server_name 〇〇vs.sakura.ne.jp;  #まだドメインの色々していないので
                location / {
                        proxy_pass http://127.0.0.1:3500;
                }
        }

VPSにアプリをクローンしていなかったのでクローンする。
⑥rbenvをインストールするが、エラー。

$ rbenv install 3.1.2
To follow progress, use 'tail -f /tmp/ruby-build.20240421172538.2787569.log' or pass --verbose
Downloading ruby-3.1.2.tar.gz...
-> https://cache.ruby-lang.org/pub/ruby/3.1/ruby-3.1.2.tar.gz
Installing ruby-3.1.2...

BUILD FAILED (Debian 12 using ruby-build 20230904)

Inspect or clean up the working tree at /tmp/ruby-build.20240421172538.2787569.V40ybm
Results logged to /tmp/ruby-build.20240421172538.2787569.log

Last 10 log lines:
 97% [895/917]  transient_heap.c
 97% [896/917]  util.c
 97% [897/917]  variable.c
 97% [898/917]  version.c
 98% [899/917]  vm.c
 98% [900/917]  vm_args.c
 98% [901/917]  vm_backtrace.c
 98% [902/917]  vm_dump.c
Killed
make: *** [uncommon.mk:572: rdoc] Error 137

RUBY_CONFIGURE_OPTS=--disable-install-doc rbenv install 3.1.2このコマンドで以下のようにインストールできた。

$ RUBY_CONFIGURE_OPTS=--disable-install-doc rbenv install 3.1.2
To follow progress, use 'tail -f /tmp/ruby-build.20240421173650.2800420.log' or pass --verbose
Downloading ruby-3.1.2.tar.gz...
-> https://cache.ruby-lang.org/pub/ruby/3.1/ruby-3.1.2.tar.gz
Installing ruby-3.1.2...
Installed ruby-3.1.2 to /home/debian/.rbenv/versions/3.1.2

$ bundle installで必要なgemをインストール。
VPS$ rails sでサーバーを立ち上げ、確認。

シークレットキーベース

credentialファイルを編集
bin/rails credentials:editを実行とrailsにあるも、エラー。

#エラー内容
No $EDITOR to open file in. Assign one like this:
#以下省略

EDITOR="vim" bin/rails credentials:editを実行。

$ EDITOR="vim" bin/rails credentials:edit
Adding config/master.key to store the encryption key: **********************:←ここにキーが表示

Save this in a password manager your team can access.

If you lose the key, no one, including you, can access anything encrypted with it.

      create  config/master.key

Couldn't decrypt config/credentials.yml.enc. Perhaps you passed the wrong key?

create config/master.keyが作成される。しかし、このキーではなく開発環境(今回はmac)内config/master.keyのキーをコピペしてVPM内のconfig/master.key内にペーストする。

$ export RAILS_ENV=productionでproductionモードへ変更する。
railsコンソールで確認。

$ rails c
Loading production environment (Rails 7.0.8)
irb(main):001> Rails.env
=> "production"

rails db:migrateマイグレーションファイルを作成する。

11 rails db:seedでseed.rbファイルを反映。

12 $ sqlite3 db/production.sqlite3でDBが作成されているか確認。

13 DBが作成されていたので、rails sでサーバーを立ち上げ確認するもエラー

14 コンパイルしてないことが原因だったので$ RAILS_ENV=production rails assets:precompileを実行しコンパイル
※この時点でブラウザを確認すると、画像表示されず、CSSも表示されずの状態。

15 /pubricのファイルは読み込む設定をしていないので、railsかnginxで設定する。今回はrailsで設定する。
config/enviroments/production.rbを編集しconfig.public_file_server.enabled = trueにする。

config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present?
# 上記を編集し以下に変更

config.public_file_server.enabled = true

CSS及び画像が表示された。

しかしログインや新規登録ができない問題。

$ tail -f log/production.logでlogを確認。

FATAL -- : [3ff1dbb3-dcee-4002-be20-ab02b739b02d]   
[3ff1dbb3-dcee-4002-be20-ab02b739b02d] ActionController::InvalidAuthenticityToken (HTTP Origin header (http://ik1-343-31774.vs.sakura.ne.jp) didn't match request.base_url (http://127.0.0.1:3500)):

Nginxをリバースプロキシとして利用

$ sudo vim /etc/nginx/nginx.confを編集し'proxy_set_header X-Forwarded-Host $host;'を追加する。

server{
                server_name ik1-343-31774.vs.sakura.ne.jp;
                proxy_set_header X-Forwarded-Host $host;
                location / {
                        proxy_pass http://127.0.0.1:3500;
                }
        }

参考: Nginxによるリバースプロキシの設定方法 #nginx - Qiita

$ sudo systemctl reload nginxコマンドでnginxをリスタートする。
アカウント登録は可能となったが、添付してアップロードした画像ファイルが以下のように反映されない。

config/strage.ymlを編集し、storageの直下に保存される設定をpublic/storageに保存されるよう書き換える。

local:
  service: Disk
  root: <%= Rails.root.join("public/storage") %>

#元は("storage")だけだった

表示されず。logを見ると、

 LoadError (Could not open library 'vips.so.42': vips.so.42: cannot open shared object file: No such file or directory.
Could not open library 'libvips.so.42': libvips.so.42: cannot open shared object file: No such file or directory.

libvipsをインストールしないといけないとのこと。

$ sudo apt-get update
$ sudo apt-get install libvips

これで終了。

次回はドメインを当てていく。