1

I did setup a docker-compose file that connects my app to a mongoDB database. My problem is that the database seems to never be initialized at first. My script is not executed and even tho' I can send some requests to the container, I only get connection refused errors due to authentification.

I did follow exactly this thread and I don't know what I'm missing out! (the db folder is on the same level as my docker-compose.yml)

Looking for some help on this one, thanks!

edit: None of the logs I did put in the init script are showing in the console, that's how I went to the conclusion that the file is not executed at all.

Here is my docker-compose file:


services:
  mongo:
    image: mongo:latest
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: admin
      MONGO_INITDB_DATABASE: test
    volumes:
      - ./db:/docker-entrypoint-initdb.d
      - ./db-data:/data/db
    ports:
      - 27017:27017
    networks:
      - api1

  app:
    restart: always
    build:
      context: .
    environment:
      DB_HOST: localhost
      DB_PORT: 27017
      DB_NAME: test
      DB_USER: developer
      DB_PASS: developer
      PORT: 3000
    ports:
      - 3000:3000
    networks:
      - api1
    depends_on:
      - mongo
    command: npm start
networks:
  api1:
    driver: bridge

Here is my init scipt:

/* eslint-disable no-undef */

try {
  print("CREATING USER")
  db.createUser(
    {
      user: "developer",
      pwd: "developer",
      roles: [{ role: "readWrite", db: "test" }]
    }
  );
} catch (error) {
  print(`Failed to create developer db user:\n${error}`);
}

And my dockerfile:

FROM node:10 as builder

RUN mkdir /home/node/app
WORKDIR /home/node/app

# Install dependencies
COPY package.json yarn.lock ./
RUN yarn install && yarn cache clean

# Copy source scripts
COPY . .

RUN yarn build

FROM node:10-alpine

RUN mkdir -p /home/node/app
WORKDIR /home/node/app

COPY --from=builder --chown=node:node /home/node/app .

USER node
EXPOSE 3000
CMD ["node", "./build/bundle.js"]
Alex Mass
  • 171
  • 1
  • 11
  • 6
    The code in the docker-entrypoint-init.d folder is only executed if the database has never been initialized before (I.e. if the /data/dB folder is empty. As such, delete the mounted ./db folder in your host machine (it will get recreated automatically) before doing docker-compose up. This will cause your scripts to be run. – camba1 Jun 13 '20 at 01:44

0 Answers0