Running a script from a mongodb docker-container

I have script that restores the database

mongorestore --port 27017 --db myapp `pwd`/db-dump/myapp

I want to run this in a short lived docker-container using the image mvertes/alpine-mongo.

  • How to change the Docker image installation directory on Mac?
  • Makefile fails executing sudo docker kill
  • Running ServiceBus in windows docker container
  • boot2docker / docker “Error. image library/.:latest not found”
  • How to fix docker so that it stops messing with android studio from connecting to emulator in OSX
  • AWS Elastic Beanstalk container_commands in Python 3.4 Docker Container
  • To run a shortlived container the --rmis used:

    docker run --rm --name mongo -p 27017:27017 \
      -v /data/db:/data/db \

    But how do I execute my script in the same command?

  • Bitbucket Pipelines - access to another container
  • Docker Compose and execute command on starting container
  • HEALTHCHECK of a Docker container running Celery tasks?
  • Two WordPress Containers on Kitematic
  • Error “DNS message ID mismatch” while pulling image
  • cannot remove docker image, error response from daemon
  • One Solution collect form web for “Running a script from a mongodb docker-container”

    Check out the docker run reference:

     $ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

    You can pass in the command you wish to execute. In your case, this could be the restore script. You must consider two things, though.

    • The script is not part of the container, so you need to mount into the container.
    • Specifying a command overwrites the CMD directive in the Dockerfile.

    If you look at the Dockerfile, you see this as its last line:

    CMD [ "mongod" ]

    This means the default command that the container executes is mongod. When you specify a command for docker run, you “replace” this with the command you pass in. In your case: Passing in the restore script will overwrite mongod, which means Mongo never starts and the script will fail.

    You have two options:

    1. Start one container with the database and another one with the restore script.
    2. Try to chain the commands.

    Since you want to run this in a short-lived container, option 2 might be better suited for you. Just remember to start mongod with the --fork flag to run it in daemon mode.

    $ docker run --rm --name mongo -p 27017:27017 \
    -v /data/db:/data/db \
    -v "$(pwd)":/mnt/pwd \
    mvertes/alpine-mongo "mongod --fork && /mnt/pwd/"

    Hopefully, this is all it takes to solve your problem.

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.