カクカクしかじか

技術的なアレコレ

Docker環境のmongoidを使ったRailsアプリでDBに接続出来ないときの解決法

経緯

現場Railsのタスク管理アプリをDocker環境+mongoidで作っていて、タスクの保存画面を作成していたところ、タスクのcreateでエラーに遭遇しました。

発生したエラー

Docker環境上でRailsのDB(MongoDB)に接続出来てなさそう... image.png

発生環境

解決法

こちらの記事にそのまんまの回答が...
要するにdocker-compose.ymlで指定している db というサービス名を mongoid.ymlで host に指定しろ!ということらしい?です。

stackoverflow.com

エラー解消前のファイル

mongoid.yml

development:
  # Configure available database clients. (required)
  clients:
    # Defines the default client. (required)
    default:
      # Defines the name of the default database that Mongoid can connect to.
      # (required).
      database: app_development
      # Provides the hosts the default client can connect to. Must be an array
      # of host:port pairs. (required)
      hosts:
        - localhost:27017
      options:
        # Note that all options listed below are Ruby driver client options (the mongo gem).
        # Please refer to the driver documentation of the version of the mongo gem you are using
        # for the most up-to-date list of options.
        #
        # Change the default write concern. (default = { w: 1 })
        # write:
        #   w: 1

        # Change the default read preference. Valid options for mode are: :secondary,
        # :secondary_preferred, :primary, :primary_preferred, :nearest
        # (default: primary)
        # read:
        #   mode: :secondary_preferred
        #   tag_sets:
        #     - use: web

        # The name of the user for authentication.
        # user: 'user'

        # The password of the user for authentication.
        # password: 'password'

        # The user's database roles.
        # roles:
        #   - 'dbOwner'

        # Change the default authentication mechanism. Valid options are: :scram,
        # :mongodb_cr, :mongodb_x509, and :plain. Note that all authentication
        # mechanisms require username and password, with the exception of :mongodb_x509.
        # Default on mongoDB 3.0 is :scram, default on 2.4 and 2.6 is :plain.
        # auth_mech: :scram

        # The database or source to authenticate the user against.
        # (default: the database specified above or admin)
        # auth_source: admin

        # Force a the driver cluster to behave in a certain manner instead of auto-
        # discovering. Can be one of: :direct, :replica_set, :sharded. Set to :direct
        # when connecting to hidden members of a replica set.
        # connect: :direct

        # Changes the default time in seconds the server monitors refresh their status
        # via ismaster commands. (default: 10)
        # heartbeat_frequency: 10

        # The time in seconds for selecting servers for a near read preference. (default: 0.015)
        # local_threshold: 0.015

        # The timeout in seconds for selecting a server for an operation. (default: 30)
        # server_selection_timeout: 30

        # The maximum number of connections in the connection pool. (default: 5)
        # max_pool_size: 5

        # The minimum number of connections in the connection pool. (default: 1)
        # min_pool_size: 1

        # The time to wait, in seconds, in the connection pool for a connection
        # to be checked in before timing out. (default: 5)
        # wait_queue_timeout: 5

        # The time to wait to establish a connection before timing out, in seconds.
        # (default: 5)
        # connect_timeout: 5

        # The timeout to wait to execute operations on a socket before raising an error.
        # (default: 5)
        # socket_timeout: 5

        # The name of the replica set to connect to. Servers provided as seeds that do
        # not belong to this replica set will be ignored.
        # replica_set: name

        # Whether to connect to the servers via ssl. (default: false)
        # ssl: true

        # The certificate file used to identify the connection against MongoDB.
        # ssl_cert: /path/to/my.cert

        # The private keyfile used to identify the connection against MongoDB.
        # Note that even if the key is stored in the same file as the certificate,
        # both need to be explicitly specified.
        # ssl_key: /path/to/my.key

        # A passphrase for the private key.
        # ssl_key_pass_phrase: password

        # Whether or not to do peer certification validation. (default: true)
        # ssl_verify: true

        # The file containing a set of concatenated certification authority certifications
        # used to validate certs passed from the other end of the connection.
        # ssl_ca_cert: /path/to/ca.cert


  # Configure Mongoid specific options. (optional)
  options:
    # Includes the root model name in json serialization. (default: false)
    # include_root_in_json: false

    # Include the _type field in serialization. (default: false)
    # include_type_for_serialization: false

    # Preload all models in development, needed when models use
    # inheritance. (default: false)
    # preload_models: false

    # Raise an error when performing a #find and the document is not found.
    # (default: true)
    # raise_not_found_error: true

    # Raise an error when defining a scope with the same name as an
    # existing method. (default: false)
    # scope_overwrite_exception: false

    # Raise an error when defining a field with the same name as an
    # existing method. (default: false)
    # duplicate_fields_exception: false

    # Use Active Support's time zone in conversions. (default: true)
    # use_activesupport_time_zone: true

    # Ensure all times are UTC in the app side. (default: false)
    # use_utc: false

    # Set the Mongoid and Ruby driver log levels when not in a Rails
    # environment. The Mongoid logger will be set to the Rails logger
    # otherwise.(default: :info)
    # log_level: :info

    # Control whether `belongs_to` association is required. By default
    # `belongs_to` will trigger a validation error if the association
    # is not present. (default: true)
    # belongs_to_required_by_default: true

    # Application name that is printed to the mongodb logs upon establishing a
    # connection in server versions >= 3.4. Note that the name cannot exceed 128 bytes.
    # app_name: MyApplicationName

    # Use background indexes by default if `background` option not specified. (default: false)
    # background_indexing: false
test:
  clients:
    default:
      database: app_test
      hosts:
        - localhost:27017
      options:
        read:
          mode: :primary
        max_pool_size: 1

エラー解消後のファイル

mongoid.yml

development:
  # Configure available database clients. (required)
  clients:
    # Defines the default client. (required)
    default:
      # Defines the name of the default database that Mongoid can connect to.
      # (required).
      database: app_development
      # Provides the hosts the default client can connect to. Must be an array
      # of host:port pairs. (required)
      hosts:
        - db:27017 # ここがポイント!localhostではなくdocker-compose.ymlと合わせてdbにする
      options:
        # Note that all options listed below are Ruby driver client options (the mongo gem).
        # Please refer to the driver documentation of the version of the mongo gem you are using
        # for the most up-to-date list of options.
        #
        # Change the default write concern. (default = { w: 1 })
        # write:
        #   w: 1

        # Change the default read preference. Valid options for mode are: :secondary,
        # :secondary_preferred, :primary, :primary_preferred, :nearest
        # (default: primary)
        # read:
        #   mode: :secondary_preferred
        #   tag_sets:
        #     - use: web

        # The name of the user for authentication.
        # user: 'user'

        # The password of the user for authentication.
        # password: 'password'

        # The user's database roles.
        # roles:
        #   - 'dbOwner'

        # Change the default authentication mechanism. Valid options are: :scram,
        # :mongodb_cr, :mongodb_x509, and :plain. Note that all authentication
        # mechanisms require username and password, with the exception of :mongodb_x509.
        # Default on mongoDB 3.0 is :scram, default on 2.4 and 2.6 is :plain.
        # auth_mech: :scram

        # The database or source to authenticate the user against.
        # (default: the database specified above or admin)
        # auth_source: admin

        # Force a the driver cluster to behave in a certain manner instead of auto-
        # discovering. Can be one of: :direct, :replica_set, :sharded. Set to :direct
        # when connecting to hidden members of a replica set.
        # connect: :direct

        # Changes the default time in seconds the server monitors refresh their status
        # via ismaster commands. (default: 10)
        # heartbeat_frequency: 10

        # The time in seconds for selecting servers for a near read preference. (default: 0.015)
        # local_threshold: 0.015

        # The timeout in seconds for selecting a server for an operation. (default: 30)
        # server_selection_timeout: 30

        # The maximum number of connections in the connection pool. (default: 5)
        # max_pool_size: 5

        # The minimum number of connections in the connection pool. (default: 1)
        # min_pool_size: 1

        # The time to wait, in seconds, in the connection pool for a connection
        # to be checked in before timing out. (default: 5)
        # wait_queue_timeout: 5

        # The time to wait to establish a connection before timing out, in seconds.
        # (default: 5)
        # connect_timeout: 5

        # The timeout to wait to execute operations on a socket before raising an error.
        # (default: 5)
        # socket_timeout: 5

        # The name of the replica set to connect to. Servers provided as seeds that do
        # not belong to this replica set will be ignored.
        # replica_set: name

        # Whether to connect to the servers via ssl. (default: false)
        # ssl: true

        # The certificate file used to identify the connection against MongoDB.
        # ssl_cert: /path/to/my.cert

        # The private keyfile used to identify the connection against MongoDB.
        # Note that even if the key is stored in the same file as the certificate,
        # both need to be explicitly specified.
        # ssl_key: /path/to/my.key

        # A passphrase for the private key.
        # ssl_key_pass_phrase: password

        # Whether or not to do peer certification validation. (default: true)
        # ssl_verify: true

        # The file containing a set of concatenated certification authority certifications
        # used to validate certs passed from the other end of the connection.
        # ssl_ca_cert: /path/to/ca.cert


  # Configure Mongoid specific options. (optional)
  options:
    # Includes the root model name in json serialization. (default: false)
    # include_root_in_json: false

    # Include the _type field in serialization. (default: false)
    # include_type_for_serialization: false

    # Preload all models in development, needed when models use
    # inheritance. (default: false)
    # preload_models: false

    # Raise an error when performing a #find and the document is not found.
    # (default: true)
    # raise_not_found_error: true

    # Raise an error when defining a scope with the same name as an
    # existing method. (default: false)
    # scope_overwrite_exception: false

    # Raise an error when defining a field with the same name as an
    # existing method. (default: false)
    # duplicate_fields_exception: false

    # Use Active Support's time zone in conversions. (default: true)
    # use_activesupport_time_zone: true

    # Ensure all times are UTC in the app side. (default: false)
    # use_utc: false

    # Set the Mongoid and Ruby driver log levels when not in a Rails
    # environment. The Mongoid logger will be set to the Rails logger
    # otherwise.(default: :info)
    # log_level: :info

    # Control whether `belongs_to` association is required. By default
    # `belongs_to` will trigger a validation error if the association
    # is not present. (default: true)
    # belongs_to_required_by_default: true

    # Application name that is printed to the mongodb logs upon establishing a
    # connection in server versions >= 3.4. Note that the name cannot exceed 128 bytes.
    # app_name: MyApplicationName

    # Use background indexes by default if `background` option not specified. (default: false)
    # background_indexing: false
test:
  clients:
    default:
      database: app_test
      hosts:
        - db:27017 # ここがポイント!localhostではなくdocker-compose.ymlと合わせてdbにする
      options:
        read:
          mode: :primary
        max_pool_size: 1

解決後の画面

正常にデータが保存出来たことを確認。

image.png

最後に

Docker環境でアプリを動かすときは、ローカルで動かすとき以上に各設定ファイルに記載する内容の意味をきちんと理解していないとハマることを思い知りました...
Dockerの勉強もミドルウェアそのものの設定周りも改めて勉強したいと思います!