Amaarockz
Amaarockz

Reputation: 4674

Unable to run a script inside docker compose

I have a docker compose file which on up, will be starting a mongo service. What I want to do is as soon as it starts the service, I want to create a database called 'abc' and create a collection 'xyz' into it.

This is what I have tried so far

docker-compose file

services:

  database: 
    image: mongo
    ports:
      - 27017:27017
    command: sh initialSetup.sh

I get the below error

Not sure why is that not able to open the script

enter image description here initialSetup.sh file

#!/bin/sh
mongo < mongoInitialSetup.js

and mongoInitialSetup.js

conn = new Mongo();
db = db.getSiblingDB('abc');
db.createCollection('xyz', {});

Add-on: It would be really great if someone could help me get this done with just the bash script without using the js file

Thanks in advance

Upvotes: 1

Views: 694

Answers (1)

Amaarockz
Amaarockz

Reputation: 4674

The below solution worked

services:

  database: 
    image: mongo
    env_file: .env
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_DATABASE: ${DATABASE_NAME}
    volumes:
      - ./initialSetup.sh:/docker-entrypoint-initdb.d/initialSetup.sh

and in the initialSetup.sh, I had

mongo -- "$MONGO_INITDB_DATABASE" <<EOF
    db.createCollection('images', {});
EOF

Upvotes: 1

Related Questions