Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

608
Views
Running mongorestore on Docker once the container starts

I'm trying to set up a container running MongoDB that gets populated with data using mongorestore when it starts up. The idea is to quickly set up a dummy database for testing and mocking.

My Dockerfile looks like this:

FROM mongo:bionic
COPY ./db-dump/mydatabase/* /db-dump/

and docker-compose.yml looks like this:

version: "3.1"
  
services:
  mongo:
    build: ./mongo
    command: mongorestore -d mydatabase ./db-dump
    ports:
      - "27017:27017"

If I run this with docker-compose up, it pauses for a while and then I get an error saying:

error connecting to host: could not connect to server: server selection error: server selection timeout, current topology: { Type: Single, Servers: [{ Addr: localhost:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : dial tcp 127.0.0.1:27017: connect: connection refused }, ] }

Opening a CLI on the container and running the exact same command works without any issues, however. I've tried adding -h with the name of the container or 127.0.0.1, and it doesn't make a difference. Why isn't this command able to connect when it works fine once the container is running?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

There is a better way than overriding the default command - using /docker-entrypoint-initdb.d:

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

[Source]

So you simply write that command into a file named mongorestore.sh:

mongorestore -d mydatabase /db-dump

and then mount it inside along with the dump file:

version: "3.1"
  
services:
  mongo:
    image: mongo:bionic
    ports:
      - "27017:27017"
    volumes:
      - ./mongorestore.sh:/docker-entrypoint-initdb.d/mongorestore.sh
      - ./db-dump:/db-dump

You don't even need a Dockerfile.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!