title: How do I seed a mongo database using docker-compose?
body: <p>I am trying to distribute a set of connected applications running in several linked containers that includes a mongo database that is required to:</p>
  
  <ul>
  <li>be distributed containing some seed data;</li>
  <li>allow users to add additional data.</li>
  </ul>
  
  <p>Ideally the data will also be persisted in a linked data volume container.</p>
  
  <p>I can get the data into the <code>mongo</code> container using a <code>mongo</code> base instance that doesn't mount any volumes (dockerhub image: <code>psychemedia/mongo_nomount</code> - this is essentially the base mongo Dockerfile without the <code>VOLUME /data/db</code> statement) and a <code>Dockerfile</code> config along the lines of:</p>
  
  <pre><code>ADD . /files
  WORKDIR /files
  RUN mkdir -p /data/db &amp;&amp; mongod --fork --logpath=/tmp/mongodb.log &amp;&amp; sleep 20 &amp;&amp; \
  mongoimport  --db testdb --collection testcoll  --type csv --headerline --file ./testdata.csv  #&amp;&amp; mongod --shutdown
  </code></pre>
  
  <p>where <code>./testdata.csv</code> is in the same directory (<code>./mongo-with-data</code>) as the Dockerfile.</p>
  
  <p>My docker-compose config file includes the following:</p>
  
  <pre><code>mongo:
    #image: mongo
    build: ./mongo-with-data
    ports:
      - "27017:27017"
    #Ideally we should be able to mount this against a host directory
    #volumes:
    #  - ./db/mongo/:/data/db
    #volumes_from:
    #  - devmongodata
  
  #devmongodata:
  #    command: echo created
  #    image: busybox
  #    volumes: 
  #       - /data/db
  </code></pre>
  
  <p>Whenever I try to mount a VOLUME it seems as if the original seeded data - which is stored in <code>/data/db</code> - is deleted. I guess that when a volume is mounted to <code>/data/db</code> it replaces whatever is there currently. </p>
  
  <p>That said, the <a href="https://docs.docker.com/userguide/dockervolumes/" rel="noreferrer">docker userguide</a> suggests that: <em>Volumes are initialized when a container is created. If the container’s base image contains data at the specified mount point, that existing data is copied into the new volume upon volume initialization</em>? So I expected the data to persist if I placed the VOLUME command after the seeding <code>RUN</code> command?</p>
  
  <p>So what am I doing wrong?</p>
  
  <p>The long view is that I want to automate the build of several linked containers, and then distribute a <code>Vagrantfile</code>/docker-compose YAML file that will fire up a set of linked apps, that includes a pre-seeded <code>mongo</code> database with a (partially pre-populated) persistent data container.</p>