Search code examples
mongodbdockermongo-shellmongoimport

dockerfile - CMD mongoimport


FROM mongo

COPY . /data/db2/

# Expose the MongoDB port
EXPOSE 27017
CMD mongoimport --db test --collection data --file /data/db2/data.json

The copy command copy data.json file

when Im trying to put the mongoimport in the CMD directive Im getting this error:

docker logs:

error connecting to host: failed to connect to mongodb://localhost/: server selection error: server selection timeout, current topology: { Type: Single, Servers: [{ Addr: localhost:27017, Type: Unknown, Last error: connection() error occurred during connection handshake: dial tcp 127.0.0.1:27017: connect: connection refused }, ] }

when Im trying to connect to container shell, and run mongosh I get this error:

MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

the weird part is when Im not putting that CMD Directive, I tried to connect to the container shell and run this command, It worked just fined.

any ideas?


Solution

  • When you use CMD mongoimport .. you overwrite the original which is CMD ["mongod"], which would start the database. So your current example never starts the database and can therefore not connect.

    If you want to to initialize/restore a database at startup there is a /docker-entrypoint-initdb.d directory in the container image you can use. Checkout Import Data on MongoDB using Docker-Compose or How to create a DB for MongoDB container on start up? for a couple of examples.