How do I add seed data when working with Docker Compose?

I am working on an app, and…

  • My docker-compose.yaml lists two services. One my golang app and second mongo.
  • My app when start initializes the database, which creates a database foo, and collection bar.

I want that collection to be already populated so that when it start, there is something to fiddle with.

I have learned about mongo-init.js, and want to use it for the same.

My docker-compose.yml:

version: '3'
services: 
    # skipped some lines
    mongo:
        image: "mongo:4.2"
        ports: 
            - "27017:27017"
        volumes: 
            - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro

My mongo-init.js:

use foo;
db.bar.insertMany([
    { "id": "bd7b69fa-9207-4996-91cd-b7eec3fce21b", "body": "This is the first entry..", "created": "2020-07-16 18:28:55.933778455 +0000 UTC", "modified": "2020-07-16 18:28:55.933778455 +0000 UTC", "author": "sntshk" },
    { "id": "8c002a9b-6532-4125-8b58-e2af55a7d60e", "body": "This is the second entry..", "created": "2020-07-16 18:28:55.933778455 +0000 UTC", "modified": "2020-07-16 18:28:55.933778455 +0000 UTC", "author": "sntshk" },
    { "id": "70032cd2-0c22-41cf-bf02-b77f52dcdb76", "body": "This is the third entry..", "created": "2020-07-16 18:28:55.933778455 +0000 UTC", "modified": "2020-07-16 18:28:55.933778455 +0000 UTC", "author": "sntshk" },
    { "id": "88d9655b-8364-4062-9153-ad35766d3eb9", "body": "This is the fourth entry..", "created": "2020-07-16 18:28:55.933778455 +0000 UTC", "modified": "2020-07-16 18:28:55.933778455 +0000 UTC", "author": "sntshk" },
    { "id": "6dddde02-02fa-4027-b469-ab2e3e7dea62", "body": "This is the fifth entry..", "created": "2020-07-16 18:28:55.933778455 +0000 UTC", "modified": "2020-07-16 18:28:55.933778455 +0000 UTC", "author": "sntshk" },
]);

Can you help me out? What do you suggest?

Hi @sntshk,

I believe there are several ways to do it. I suggest to explore the command property to specify a command to be run in the container to execute a shell command:

https://docs.docker.com/compose/compose-file/#command

If you want you can use a string or mount/copy a js file to the container.

Please let me know if you need more assistance.

Best regards,
Pavel