LoginSignup
3
3

More than 3 years have passed since last update.

Production環境でAction Cable + Redis(ElastiCache)を使用する

Last updated at Posted at 2020-12-10

毎度デプロイ時に迷走するので、自分用のメモです。
問題点等があれば、ご指摘頂けますと幸いです。

前提

  • 開発環境でのRedisは問題なく動作すること
  • アプリケーションへのドメイン設定が完了していること
  • ElastiCacheの設定が完了していること
  • .envを導入済みであること

使用バージョン

  • Ruby:2.6.5
  • Ruby on Rails: 6.0.3

アプリケーション側

/config/routes.rb
Rails.application.routes.draw do
  # action cable
  mount ActionCable.server => '/cable'
end
.env
REDIS_HOST="【ElastiCacheのエンドポイント】"
REDIS_PORT="6379"
/config/initializers/redis.rb
Redis.new(:host => ENV['REDIS_HOST'], :port => ENV['REDIS_PORT'])
/config/environments/production.rb
config.action_cable.disable_request_forgery_protection = true
config.action_cable.allowed_request_origins = ['https://【ドメイン名】, %r{https://【ドメイン名】.*}, 'http://【ドメイン名】', %r{http://【ドメイン名】.*}]
/config/environments/production.rb
  config.session_store :redis_store, {
    :servers => {
        :host => ENV['REDIS_HOST'],
        :port => ENV['REDIS_PORT'],
        :db => 0,
        :namespace => 'sessions'
    },
    :expire_after => 1.days
  }
/config/cable.yml
production:
  adapter: redis
  port: 6379
  url: redis://<%= ENV['REDIS_HOST'] %>

サーバー側

nginxの設定

アプリケーション名.conf
upstream unicorn_server {
    server unix:/var/www/projects/【アプリケーションディレクトリ】/tmp/sockets/.unicorn.sock
    fail_timeout=0;
}

server {
    listen 80;
    client_max_body_size 4G;
    server_name 【ドメイン名】;
    gzip on;

    keepalive_timeout 5;

    # Location of our static files
    root /var/www/projects/【アプリケーションディレクトリ】/public;

    location ~ ^/assets/ {
        root /var/www/projects/【アプリケーションディレクトリ】/public;
        location ~ .*.(js|css|html|svg)+$ {
            gzip_static on;
            gunzip on;
        }
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        if (!-f $request_filename) {
            proxy_pass http://unicorn_server;
            break;
        }
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /var/www/projects/【アプリケーションディレクトリ】/public;
    }

   location /cable {
        proxy_pass http://unicorn_server;
        proxy_http_version 1.1;
        proxy_set_header Upgrade websocket;
        proxy_set_header Connection Upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

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