LoginSignup
0
0

More than 1 year has passed since last update.

DockerのRailsアプリからRedisサーバに接続したい

Last updated at Posted at 2022-08-27

はじめに

docker環境で起動しているrailsアプリからホストで起動しているredisサーバに接続したい。
なお、前提として、dockerでのrailsアプリの環境構築が完了しているものとする。

環境

  • ローカル環境
    • macOS
  • docker環境
    • ruby 3.1.2
    • Rails 7.0.3.1

手順

1. ローカルホストでredisを起動する

まずredisをインストールするために、下記のコマンドを実行

brew install redis

インストールされているか確認する
redisがあればOK

$ brew list | grep redis
redis

redisサーバをバックグラウンドで起動

brew services start redis

redisのクライアントコマンドで以下のように、接続確認を行い、"PONG"が返ってくることを確認

$ redis-cli ping
PONG

2. rails側にredisを導入する

Gemfileに以下を記述し、appコンテナに入る
bundle install を実行する

gem ‘redis-rails’

インストールされている確認
以下のようなものが入っていればOK

root@[コンテナID]:/app# gem list | grep redis
redis (4.8.0)
redis-actionpack (5.3.0)
redis-activesupport (5.3.0)
redis-rack (2.1.4)
redis-rails (5.0.2)
redis-store (1.9.1)

3. いざ!接続してみる

appコンテナに入り、rails cを実行しコンソールを立ち上げる。
Redis.newを実行する。url部分については、dockerコンテナ内からホストマシンのlocalhostに接続するためdocker.for.mac.localhostと指定する。(参考:https://qiita.com/Asayu123/items/ccfe4ccfc417ce57f445)
ポートはデフォルトの6379としています。

irb(main):004:0> redis = Redis.new(url:"redis://docker.for.mac.localhost:6379")
=> #<Redis client v4.8.0 for redis://docker.for.mac.localhost:6379/0>

1.のときと同様に接続確認を行う

irb(main):005:0> redis.ping
=> "PONG"

4. Redisを操作してみる

操作について: https://github.com/redis/redis-rb
railsコンソール上のまま、以下のように書き込んでみる。

irb(main):015:0> redis.set "hogekey", "Hello"
=> "OK"

そしてローカルから確認してみると、保存されている!

$ redis-cli
127.0.0.1:6379> get "hogekey"
"Hello"

番外編

redis-cliでクライアントを立ち上げようとしたときにエラーが出る。

$ redis-cli ping
(error) MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.

そもそもredisはインメモリデータベースの一種である。(そのため、高速な処理を行うことが特徴。)
ただ、サーバが停止するとメモリが解放され、データが消えてしまうので、データの永続化をおこなっている。具体的には、定期的にスナップショットを作成し、起動時にそれを読み込むことで復元をしている。今回はどうやら、そのディスクへの書き出しができないとのことでエラーが発生しているとのこと。
redisサーバを再起動することで解決。

$ brew services restart redis 

参考:

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