mongo icon indicating copy to clipboard operation
mongo copied to clipboard

Moped::Errors::ConnectionFailure in

Open sandeshsoni opened this issue 11 years ago • 2 comments

Unable to use / configure mongo and rails I get error Could not connect to a primary node for replica set #<Moped::Cluster:69855863078300 @seeds=[<Moped::Node resolved_address="127.0.0.1:27017">]>

when open in browser http://0.0.0.0:27017 It looks like you are trying to access MongoDB over HTTP on the native driver port.

Dockerfile

FROM rails:4.2.1 MAINTAINER Sandesh Soni, [email protected] RUN apt-get update -qq && apt-get install -y build-essential libpq-dev RUN mkdir /gmv WORKDIR /gmv ADD Gemfile /gmv/Gemfile RUN bundle install ADD . /gmv

docker-compose file

app: build: . command: bundle exec rails s -p 3000 -b '0.0.0.0' volumes: - .:/gmv ports: - "3000:3000" links: - db - redis db: image: mongo ports:

  • "27017:27017"

redis: image: redis ports:

  • "6379"

sandeshsoni avatar May 17 '15 12:05 sandeshsoni

@sandeshsoni I think this is probably a ruby config issue. How are you trying to connect to mongo in your app? if you are using the mongo gem you need to have it connect with a replicaset only when its mongo is configured to be one otherwise you need to use a different class. I do this with something like this in my initializer (forgive any typos I quickly grabbed and scrubbed some of our internal libs for here):

def init_mongo_with_retry(max_retries)
  retries=0
  require 'yaml'
mongo_config = YAML.load_file('<PATH_TO_SOME_YML_CONFIG>')[ENV[RACK_ENV]]['mongo']
  begin
    # if we have secure_config['mongo']['rs'] we connect with the mongo
    # replicaset client/class otherwise use basic
    if mongo_config['rs']
      $MONGO_CONN = Mongo::MongoReplicaSetClient.new(
        ["#{mongo_config['host']}:#{mongo_config['port']}"],
        :read => mongo_config['read'].to_sym,
        :name => mongo_config['rs'],
        :pool_size => mongo_config['pool_size'],
        :connect_timeout => mongo_config['conn_timeout'],
        :op_timeout => mongo_config['op_timeout']
      )
    else
      $MONGO_CONN = Mongo::MongoClient.new(mongo_config['host'], mongo_config['port'])
    end
    $MONGO = $MONGO_CONN.db(mongo_config['database'])
  rescue Mongo::ConnectionFailure => ex
    retries += 1
    STDERR.puts "Time: #{Time.now}, Mongo failed to connect to: #{$MONGO_CONN.seeds}, attempts: #{retries} "
    # here you can get ex.message
    raise ex if retries > max_retries
    retry
  end
end

init_mongo_with_retry(max_retries=60)

sge-babrams avatar Jun 23 '15 22:06 sge-babrams

Seems this is not a mongo image problem, but a ruby configuration issue. Feel free to ping if there is a problem with the mongo image.

yosifkit avatar Jul 02 '15 22:07 yosifkit