Docker Community Forums

Share and learn in the Docker community.

Creating and connect mongo database with Docker-Compose and MEAN Stack


(Mlenhart) #1

Hello guys and girls,
I’m developing on a Mac and I’am new to docker.
I try to dockerize my app, which is created with the MEAN-Stack( Mongo, Express, Angularjs, Nodejs ).
I have written a seperate frontend with Angularjs, and an API with Nodejs, Express and using Mongoose to connect to the Mongo-Database for executing CRUD Operarions.

Now I want to use the official mongo-image for connecting with my API and then connect this later with the frontend by using docker.
My Dockerfile for the API is:

FROM ubuntu:latest
MAINTAINER Michael
RUN apt-get update
RUN apt-get install -y nodejs nodejs-legacy npm
RUN apt-get clean
COPY ./package.json src/
RUN cd src && npm install
COPY . /src
WORKDIR src/
EXPOSE 3000
ENV NODE_ENV development
CMD [ "npm", "start" ]

And the Docker-Compose File is

version: "2"
services:
lager-server:
build:
context: .
dockerfile: Dockerfile.dev
command: npm start
depends_on:
- mongodb
volumes:
- .:/app
- /app/node_modules
ports:
- 80:3000
links:
- mongodb
mongodb:
image: mongo:latest
command: --smallfiles
ports:
- 27017:27017

I can now connect with mongoose in my app.js (API) over the link to the mongo-container

mongoose.connect(‘mongodb://mongodb/lager’);

But how can I create the database in the mongo container using docker-compose?
It seems that there is no Environment-Variable for creating the Database in the official mongo-image.
Maybe is there a way for creating the database with CMD in the Docker-Compose-file?

I am thankful for all help and information.

Michael

"UPDATE"
After reading some manuals and try to POST an JSON-Object over the API, the database lager ist automatically created. SO it is not necessary to create the database lagers manually.
Further information.
http://www.mkyong.com/mongodb/how-to-create-database-or-collection-in-mongodb/
http://www.ifdattic.com/how-to-mongodb-nodejs-docker/