Initialize data on dockerized mongo

后端 未结 5 591
無奈伤痛
無奈伤痛 2020-12-08 05:35

I\'m running a dockerized mongo container.

I\'d like to create a mongo image with some initialized data.

Any ideas?

5条回答
  •  爱一瞬间的悲伤
    2020-12-08 06:06

    First create a docker volume

    docker volume create --name mongostore
    

    then create your mongo container

    docker run -d --name mongo -v mongostore:/data/db mongo:latest
    

    The -v switch here is responsible for mounting the volume mongostore at the /data/db location, which is where mongo saves its data. The volume is persistent (on the host). Even with no containers running you will see your mongostore volume listed by

    docker volume ls
    

    You can kill the container and create a new one (same line as above) and the new mongo container will pick up the state of the previous container.

    Initializing the volume Mongo initializes a new database if none is present. This is responsible for creating the initial data in the mongostore. Let's say that you want to create a brand new environment using a pre-seeded database. The problem becomes how to transfer data from your local environment (for instance) to the volume before creating the mongo container. I'll list two cases.

    1. Local environment

      You're using either Docker for Mac/Windows or Docker Toolbox. In this case you can easily mount a local drive to a temporary container to initialize the volume. Eg:

      docker run --rm -v /Users/myname/work/mongodb:/incoming \
        -v mongostore:/data alpine:3.4 cp -rp /incoming/* /data
      

      This doesn't work for cloud storage. In that case you need to copy the files.

    2. Remote environment (AWS, GCP, Azure, ...)

      It's a good idea to tar/compress things up to speed the upload.

      tar czf mongodata.tar.gz /Users/myname/work/mongodb
      

      Then create a temporary container to untar and copy the files to the mongostore. the tail -f /dev/null just makes sure that the container doesn't exit.

      docker run -d --name temp -v mongostore:/data alpine:3.4 tail -f /dev/null
      

      Copy files to it

      docker cp mongodata.tar.gz temp:.
      

      Untar and move to the volume

      docker exec temp tar xzf mongodata.tar.gz && cp -rp mongodb/* /data
      

      Cleanup

      docker rm temp
      

    You could also copy the files to the remote host and mounting from there but I tend to avoid interacting with the remote host at all.

    Disclaimer. I'm writing this from memory (no testing).

提交回复
热议问题