質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Redis

Redisは、オープンソースのkey-valueデータストアで、NoSQLに分類されます。すべてのデータをメモリ上に保存するため、処理が極めて高速です。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

Q&A

解決済

1回答

1806閲覧

EC2内にインストールしたredisに同じEC2にあるアプリケーションから接続できない

oeiqgfodgfhps

総合スコア35

Redis

Redisは、オープンソースのkey-valueデータストアで、NoSQLに分類されます。すべてのデータをメモリ上に保存するため、処理が極めて高速です。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

0グッド

0クリップ

投稿2021/07/21 08:40

編集2021/07/21 16:02

EC2内にRedisをインストールして、そのEC2の中にあるrailsアプリから動かそうとしていますが接続がうまくいかず、ログにRedis::CannotConnectError (Error connecting to Redis on localhost:6379 (Errno::EADDRNOTAVAIL)):と出てしまいます。
エラー文からみるに接続がうまくいっていないのだと思いますが、どのように解消すればいいのかが詰まっています。ご助言お願いいたします。下記に関係がありそうなファイルを記述しておきます。(REDISの生成処理も問題があるかもしれないと思ったので、redis.rbも置いておきます。)

production.rb

ruby

1require "active_support/core_ext/integer/time" 2 3Rails.application.configure do 4 # Settings specified here will take precedence over those in config/application.rb. 5 6 # Code is not reloaded between requests. 7 config.cache_classes = true 8 9 # Eager load code on boot. This eager loads most of Rails and 10 # your application in memory, allowing both threaded web servers 11 # and those relying on copy on write to perform better. 12 # Rake tasks automatically ignore this option for performance. 13 config.eager_load = true 14 15 # Full error reports are disabled and caching is turned on. 16 config.consider_all_requests_local = false 17 18 # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 19 # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 20 # config.require_master_key = true 21 22 # Disable serving static files from the `/public` folder by default since 23 # Apache or NGINX already handles this. 24 config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 25 26 # Enable serving of images, stylesheets, and JavaScripts from an asset server. 27 # config.asset_host = 'http://assets.example.com' 28 29 # Specifies the header that your server uses for sending files. 30 # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 31 # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 32 33 # Store uploaded files on the local file system (see config/storage.yml for options). 34 config.active_storage.service = :local 35 36 # Mount Action Cable outside main process or domain. 37 # config.action_cable.mount_path = nil 38 # config.action_cable.url = 'wss://example.com/cable' 39 # config.action_cable.allowed_request_origins = [ 'http://example.com', /http://example.*/ ] 40 41 # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 42 # config.force_ssl = true 43 44 # Include generic and useful information about system operation, but avoid logging too much 45 # information to avoid inadvertent exposure of personally identifiable information (PII). 46 config.log_level = :info 47 48 # Prepend all log lines with the following tags. 49 config.log_tags = [ :request_id ] 50 51 # Use a different cache store in production. 52 # config.cache_store = :mem_cache_store 53 54 # Use a real queuing backend for Active Job (and separate queues per environment). 55 # config.active_job.queue_adapter = :resque 56 # config.active_job.queue_name_prefix = "api_practice_production" 57 58 config.action_mailer.perform_caching = false 59 60 # Ignore bad email addresses and do not raise email delivery errors. 61 # Set this to true and configure the email server for immediate delivery to raise delivery errors. 62 # config.action_mailer.raise_delivery_errors = false 63 64 # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 65 # the I18n.default_locale when a translation cannot be found). 66 config.i18n.fallbacks = true 67 68 # Send deprecation notices to registered listeners. 69 config.active_support.deprecation = :notify 70 71 # Log disallowed deprecations. 72 config.active_support.disallowed_deprecation = :log 73 74 # Tell Active Support which deprecation messages to disallow. 75 config.active_support.disallowed_deprecation_warnings = [] 76 77 # Use default logging formatter so that PID and timestamp are not suppressed. 78 config.log_formatter = ::Logger::Formatter.new 79 80 config.session_store :redis_store, servers: 'redis://localhost:6379/0', expire_in: 7.day 81 82 # Use a different logger for distributed setups. 83 # require "syslog/logger" 84 # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 85 86 if ENV["RAILS_LOG_TO_STDOUT"].present? 87 logger = ActiveSupport::Logger.new(STDOUT) 88 logger.formatter = config.log_formatter 89 config.logger = ActiveSupport::TaggedLogging.new(logger) 90 end 91 92 # Do not dump schema after migrations. 93 config.active_record.dump_schema_after_migration = false 94 95 # Inserts middleware to perform automatic connection switching. 96 # The `database_selector` hash is used to pass options to the DatabaseSelector 97 # middleware. The `delay` is used to determine how long to wait after a write 98 # to send a subsequent read to the primary. 99 # 100 # The `database_resolver` class is used by the middleware to determine which 101 # database is appropriate to use based on the time delay. 102 # 103 # The `database_resolver_context` class is used by the middleware to set 104 # timestamps for the last write to the primary. The resolver uses the context 105 # class timestamps to determine how long to wait before reading from the 106 # replica. 107 # 108 # By default Rails will store a last write timestamp in the session. The 109 # DatabaseSelector middleware is designed as such you can define your own 110 # strategy for connection switching and pass that into the middleware through 111 # these configuration options. 112 # config.active_record.database_selector = { delay: 2.seconds } 113 # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 114 # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 115end

settings.yml

session: url: redis://localhost:6379 timeout: 7200

initializers/redis.rb

ruby

1if Rails.env.test? 2 REDIS = MockRedis.new 3else 4 REDIS = Redis.new(url: Settings.session.url) 5end

redis.confの内容

protected-mode no port 6379 tcp-backlog 511 timeout 0 tcp-keepalive 300 ################################# GENERAL ##################################### daemonize no supervised no pidfile /var/run/redis_6379.pid loglevel notice logfile /var/log/redis/redis.log databases 16 always-show-logo yes ################################ SNAPSHOTTING ################################ save 900 1 save 300 10 save 60 10000 stop-writes-on-bgsave-error yes rdbcompression yes rdbchecksum yes dbfilename dump.rdb dir /var/lib/redis ################################# REPLICATION ################################# slave-serve-stale-data yes slave-read-only yes repl-diskless-sync no repl-diskless-sync-delay 5 repl-disable-tcp-nodelay no slave-priority 100 ############################# LAZY FREEING #################################### lazyfree-lazy-eviction no lazyfree-lazy-expire no lazyfree-lazy-server-del no slave-lazy-flush no ############################## APPEND ONLY MODE ############################### appendonly no appendfilename "appendonly.aof" appendfsync everysec no-appendfsync-on-rewrite no auto-aof-rewrite-percentage 100 auto-aof-rewrite-min-size 64mb aof-load-truncated yes aof-use-rdb-preamble no ################################ LUA SCRIPTING ############################### lua-time-limit 5000 ################################## SLOW LOG ################################### slowlog-log-slower-than 10000 # There is no limit to this length. Just be aware that it will consume memory. # You can reclaim memory used by the slow log with SLOWLOG RESET. slowlog-max-len 128 ################################ LATENCY MONITOR ############################## latency-monitor-threshold 0 ############################# EVENT NOTIFICATION ############################## notify-keyspace-events "" ############################### ADVANCED CONFIG ############################### hash-max-ziplist-entries 512 hash-max-ziplist-value 64 list-max-ziplist-size -2 list-compress-depth 0 set-max-intset-entries 512 zset-max-ziplist-entries 128 zset-max-ziplist-value 64 hll-sparse-max-bytes 3000 activerehashing yes client-output-buffer-limit normal 0 0 0 client-output-buffer-limit slave 256mb 64mb 60 client-output-buffer-limit pubsub 32mb 8mb 60 hz 10 aof-rewrite-incremental-fsync yes

sudo systemctl status redisで出力された内容

● redis.service - Redis persistent key-value database Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled) Drop-In: /etc/systemd/system/redis.service.d └─limit.conf Active: inactive (dead)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

AbeTakashi

2021/07/21 15:43

redisのインストール方法や起動状況がまったく書かれてないのですが、その辺は本当に問題ないのでしょうか? redis.confの内容やsudo systemctl status redis(Amazon Linux2と仮定して・・・)で表示される内容も可能な範囲で記載されると、正しい答えが出てくる可能性が高まると思います。
oeiqgfodgfhps

2021/07/21 16:03

redis.confの内容と、sudo systemctl status redisで出力された内容も記載しました。 また、redisのインストールや設定についてはhttps://www.y-hakopro.com/entry/2020/09/02/210000この記事を参考にしました
guest

回答1

0

ベストアンサー

Active: inactive (dead)

ですね。Redisが問題なく起動している場合は

Active: active (running) since 木 2021-07-22 00:57:11 JST; 8min ago

みないな表示になるはずです。

ということでRedisが正しく起動していないと思われます。

まずは sudo systemctl start redis を叩いてみましょう。

それでもだめなら
/var/log/redis/redis.log を確認して、起動しない理由を見つけて、Redisが正しく起動するようにしてください。

投稿2021/07/21 16:10

AbeTakashi

総合スコア4537

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

oeiqgfodgfhps

2021/07/22 02:08

上記コマンドを実行しても Job for redis.service failed because the control process exited with error code. See "systemctl status redis.service" and "journalctl -xe" for details というエラーが出てしまいました。 また、ログファイルを確認したのですが、起動時の日付のものは何も書き込まれていませんでした。 sudo systemctl status redisを実行してみたら、下記のような出力がありました ● redis.service - Redis persistent key-value database Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled) Drop-In: /etc/systemd/system/redis.service.d └─limit.conf Active: failed (Result: exit-code) since 木 2021-07-22 02:02:59 UTC; 53s ago Process: 11216 ExecStart=/usr/bin/redis-server /etc/redis.conf --supervised systemd (code=exited, status=1/FAILURE) Main PID: 11216 (code=exited, status=1/FAILURE) 7月 22 02:02:59 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: Starting Redis persistent key-value database... 7月 22 02:02:59 ip-10-0-10-10.ap-northeast-1.compute.internal redis-server[11216]: *** FATAL CONFIG FILE ERROR *** 7月 22 02:02:59 ip-10-0-10-10.ap-northeast-1.compute.internal redis-server[11216]: Reading the configuration file, at line 171 7月 22 02:02:59 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: redis.service: main process exited, code=exited, status=1/FAILURE 7月 22 02:02:59 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: Failed to start Redis persistent key-value database. 7月 22 02:02:59 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: Unit redis.service entered failed state. 7月 22 02:02:59 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: redis.service failed.
AbeTakashi

2021/07/22 02:21

たぶんですが FATAL CONFIG FILE ERROR と書いてるので、redis.confの記述に問題があるのではないかと思います。デフォルトから何か変更した記憶はありますか?(参考サイトどおりにやったのなら、その辺が怪しいので確認してください) 分からないのであれば一度redisをアンインストール(sudo yum remove redis)して、再インストールすればredis.confはデフォルトに戻ると思います。まずはredis.confを一切触らずに起動確認してみるといいと思いますけどね。
oeiqgfodgfhps

2021/07/22 04:04

redis.confを触らずに起動確認というのは、redis-serverコマンドを叩くだけということでしょうか??
oeiqgfodgfhps

2021/07/22 04:13

redis-cliでredisを起動し、set hoge hugaでデータのセットを行い、get hogeでhugaを取り出すことに成功しているのですが、これはredisが起動しているということにはなりませんか??
AbeTakashi

2021/07/22 06:21 編集

その状態であればredisは起動しているように見受けられますが、念のためsudo systemctl status redisを叩いてみるといいと思います。
oeiqgfodgfhps

2021/07/22 06:23

sud osystemctl status redis を叩いてみましたが、failedになっていました。 ● redis.service - Redis persistent key-value database Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled) Drop-In: /etc/systemd/system/redis.service.d └─limit.conf Active: failed (Result: exit-code) since 木 2021-07-22 04:06:40 UTC; 2h 16min ago Main PID: 12679 (code=exited, status=1/FAILURE) 7月 22 04:06:40 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: Starting Redis persistent key-value database... 7月 22 04:06:40 ip-10-0-10-10.ap-northeast-1.compute.internal redis-server[12679]: *** FATAL CONFIG FILE ERROR *** 7月 22 04:06:40 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: redis.service: main process exited, code=exited, status=1/FAILURE 7月 22 04:06:40 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: Failed to start Redis persistent key-value database. 7月 22 04:06:40 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: Unit redis.service entered failed state. 7月 22 04:06:40 ip-10-0-10-10.ap-northeast-1.compute.internal systemd[1]: redis.service failed.
AbeTakashi

2021/07/22 06:36

改めて参考サイトをみてみたのですが、起動方法が sudo redis-server /etc/redis.conf & となってましたね。おそらくこの方法で起動されていたと思います。であればたしかにsystemctlでstatusは取れないですね。通常は前にも書きましたがsudo systemctl start redisとやる方が普通かと思いますが、そのサイトがそのような方法を勧めているのかは私には分からないので・・・ 何はともあれ、たしかにRedis自体は起動してるようです。あとはなんですかね。redis://localhost:6379 となっているところをすべて redis://127.0.0.1:6379 に変えてみるとかでしょうか。これでダメなら分からないです。すいません。
oeiqgfodgfhps

2021/07/22 07:18

もしかしたらと思うのですが、railsはdockerで動かしているので、コンテナの外のec2のredisにはアクセスできないというようなことはありますでしょうか??
AbeTakashi

2021/07/22 07:35

ホストからコンテナにアクセスするにはポートフォワードの設定次第ですね。 参考 https://qiita.com/tatsuo-iriyama/items/e4bf2404411343116e3e docker ps として 0.0.0.0:6379->6379/tcp となっていれば普通にアクセスはできると思いますが。 なんか環境がややこしいですね。Dockerを使うならコンテナ間通信でDockerだけで完結させた方が良いようにも思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問