Reputation: 3072
I need to use MongoDB with Docker. Up until now i am able to create a container, start the Mongo server and access it from the host machine (via Compass). What i want to do next is import data from a script into the Mongo database that is running in the container. I'm getting the following error when trying to import the data:
Failed: error connecting to db server: no reachable servers
Where's what i'm doing...
docker-compose.yml:
version: '3.7'
services:
mongodb:
container_name: mongodb_db
build:
context: .
dockerfile: .docker/db/Dockerfile
args:
DB_IMAGE: mongo:4.0.9
ports:
- 30001:27017
environment:
MONGO_DATA_DIR: /data/db
MONGO_LOG_DIR: /dev/null
db_seed:
build:
context: .
dockerfile: .docker/db/seed/Dockerfile
args:
DB_IMAGE: mongo:4.0.9
links:
- mongodb
mongodb Dockerfile:
ARG DB_IMAGE
FROM ${DB_IMAGE}
CMD ["mongod", "--smallfiles"]
db_seedDockerfile:
ARG DB_IMAGE
FROM ${DB_IMAGE}
RUN mkdir -p /srv/tmp/import
COPY ./app/import /srv/tmp/import
# set working directory
WORKDIR /srv/tmp/import
RUN mongoimport -h mongodb -d dbName--type csv --headerline -c categories --file=categories.csv #Failed: error connecting to db server: no reachable servers
RUN mongo mongodb/dbName script.js
What am I doing wrong here? How can i solve this issue? I would like to keep the current file organisation (docker-compose, mongodb Dockerfile and db_seed Dockerfile).
Upvotes: 1
Views: 2804
Reputation: 3072
I found the reason for the issue. The import command is being executed prior to the mongo service being started. To solve this issue i created a .sh script with the import commands and execute it using ENTRYPOINT. This way the script is only executed after the db_seed container is created. Since the the db_seed container depends on the mongobd container, it will only execute the script after the mongo service is started.
db_seedDockerfile
ARG DB_IMAGE
FROM ${DB_IMAGE}
RUN mkdir -p /srv/tmp/import
COPY ./app/import /srv/tmp/import
ENTRYPOINT ["./srv/tmp/import/import.sh"]
Upvotes: 4