Note: If you have used mongoose and mongo before, your local or mlab connection URL might look like this mongodb://localhost:27017/<your_db> or mongodb://<dbuser>:<dbpassword>@ds115595.mlab.com:15595/<your_db> respectively and not mongodb://mongo:27017. This is because our mongo database service will be called mongo and since it exists in a docker container and not locally on your drive we will expose the port 27017 in its container.

Create our MongoDB service

In order to build and run a couple of services, we need to introduce a docker-compose.yml file that contains certain configurations that will allow that.

$ touch docker-compose.yml

Type this in the YAML file

# Defines our composer file version
version: "2.2"
# Define our services
services:
# This is our nodejs app built using the Dockerfile
app:
# The name of our node app container
container_name: docker_nodejs_app
# Restarts our node app whenever it fails
restart: always
# Builds the node app docker container from the local -
# Docker file we created
build: .
# Exposes the necessary ports that our node app uses
ports:
- "3000:3000"
# All the services our node app will link to -
# which in our case is only mongo
# You can other services such as a Redis
links:
# The name should be similar to the service you will build
- mongo
# Our database service called mongo
mongo:
# The name of the database container, NOTE: it is similar to the name provided
container_name: mongo
# Builds a mongo image from the docker repository
image: mongo
# Exposes the ports that Mongo uses
ports:
- "27017:27017"

To run our configurations we will use a docker-compose command...wait where did this come from? 😳

The command docker-compose comes with the Docker software, it executes the configurations in the docker-compose.yml file.

To build and run our app and mongo services, type this in your terminal

$ docker-compose up

What happens next will take a bit longer...😇...Free time...maybe make yourself a cup of coffee ☕️ or check out Twitter

What happens next, Docker:

Pulls the Mongo image from the remote Docker repository

Downloads Mongo into Dockers cache

Run instances of mongo

Builds our Node app

Runs our server and connects to the Mongo database successfully.

What next after a successful build?

You can test out the database by creating a couple of

POST requests to save data in the MongoDB database collection

GET requests to retrieve data from the database collection

PUT requests to update data in the database collection

DELETE requests to delete data in the database collection

Summary

To summarise, in this post we have:

Connected to MongoDB database service successful

Introduction to the docker-compose command

Next

In the next part:

We will host our application on Heroku

Push our repo to the Docker repository.

Other commands in Docker that will make your experience worthwhile such as: