以下の内容はhttps://otiai10.hatenablog.com/entry/2016/01/12/154230より取得しました。


docker-compose内でmongodbがFailed to connect to a master node at 0.0.0.0:27017となる

問題

docker-compose.yml

mongodb:
  container_name: mongodb
  image: mongo:3.2.0
  ports:
    - "27017:27017"
myapp:
  container_name: myapp
  build: .
  dockerfile: Dockerfile
  links:
    - mongodb # まずはもちろんこれが必要

main.rb(抜粋)

require 'mongo_mapper'
MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = 'myapp-dev'

以下のようなエラーが出る

# 略(mongodbは普通に立ってる)
mongodb  | 2016-01-12T05:47:48.839+0000 I NETWORK  [initandlisten] waiting for connections on port 27017
mongodb  | 2016-01-12T05:47:48.839+0000 I NETWORK  [HostnameCanonicalizationWorker] Starting hostname canonicalization worker
myapp    | /usr/local/bundle/gems/mongo-1.12.5/lib/mongo/mongo_client.rb:417:in `connect`: Failed to connect to a master node at localhost:27017 (Mongo::ConnectionFailure)
myapp    |    from /usr/local/bundle/gems/mongo-1.12.5/lib/mongo/mongo_client.rb:656:in `setup`
myapp    |    from /usr/local/bundle/gems/mongo-1.12.5/lib/mongo/mongo_client.rb:179:in `initialize`
myapp    |    from /usr/local/bundle/gems/mongo-1.12.5/lib/mongo/legacy.rb:52:in `initialize`
myapp    |    from main.rb:20:in `new`
myapp    |    from main.rb:20:in `<main>`
myapp exited with code 1
# アプリケーションがモンゴディビにつながってない

調査

Note: Environment variables are no longer the recommended method for connecting to linked services. Instead, you should use the link name (by default, the name of the linked service) as the hostname to connect to. See the docker-compose.yml documentation for details.

解決

# ↓うごかんやつ
# MongoMapper.connection = Mongo::Connection.new('localhost', 27017)

# ↓うごくけどno longer the recommended methodなやつ
# MongoMapper.connection = Mongo::Connection.new(ENV["MONGODB_PORT_27017_TCP_ADDR"], 27017)

# ↓どういう理屈かしらんけどhostnameがdocker-composeのservice name
MongoMapper.connection = Mongo::Connection.new('mongodb', 27017)

MongoMapper.database = 'myapp-dev'

DRYな備忘録として




以上の内容はhttps://otiai10.hatenablog.com/entry/2016/01/12/154230より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14