Getting Started With MongoDB As A Docker Container Deployment

Getting Started With MongoDB As A Docker Container Deployment

Learn how to get started with MongoDB using Docker so it can be deployed and interacted with as a container.

Learn how to get started with MongoDB using Docker so it can be deployed and interacted with as a container.

MongoDB is one of the most popular NoSQL databases on the market right now and is used heavily with Node.js development in particular. So what if you wanted to give MongoDB a spin and see what it’s all about?

There are plenty of deployment options when it comes to using MongoDB. For example, I had recently written a tutorial titled, Developing a RESTful API with Node.js and MongoDB Atlas which focused on the MongoDB cloud solution called Atlas. However, you can also install MongoDB on premise using multiple options.

In this tutorial we’re going to focus on using Docker to deploy MongoDB as a container and interact with it with the shell client.

Downloading the Latest MongoDB Docker Image

Assuming that you have Docker installed on your computer or server, we can obtain the MongoDB image from the Docker Hub container registry. There are numerous images available, each representing different versions of MongoDB or the underlying operating system that it is installed on.

The simplest solution to download our image is to execute the following:

docker pull mongo


The above command will get the latest tag which could be anything. This is great if you want to be bleeding edge, but when you’re doing realistic deployments you probably want to be in control of the versioning information. Instead, you might want to specify the tag like this:

docker pull mongo:4.0.4


At the time of writing this, MongoDB 4.0.4 is the latest version and it is what the latest tag represents. This time we’re actually specifying the 4.0.4 tag because that is what we want.

It may take a moment, but when it is done, we have an image that is ready for deployment.

Deploying an Instance of MongoDB as a Container

With the image available to us, we need to deploy it. In its simplest form, and what is outlined in the Docker Hub documentation, we can execute the following command:

docker run --name mongodb mongo:4.0.4


This command works, but there are potentially a few problems. What we’re doing is we are running a container and naming it mongodb. We aren’t running it in the background and if we wanted to connect to it, we’d have to do it from another container instance. In other words, we wouldn’t be able to connect to it from our host computer or server.

Instead, what we could do is the following:

docker run -d -p 27017-27019:27017-27019 --name mongodb mongo:4.0.4


The above command will run the container in detached mode, or in the background for us. We are also mapping the container ports with host ports so that way we can access the database from a host level application if we wanted to. The ports used were taken from the MongoDB documentation. You don’t need to map the ports in order to use MongoDB. Like I said, the port mapping is only necessary if you wish to use it from your host Mac, Windows, or Linux computer. If you plan to deploy all your applications as micro-services with Docker, then you’d be fine as long as your containers can communicate with each other.

Interacting with the MongoDB Docker Container with Basic Shell Operations

At this point in time we have a functional MongoDB deployment. Rather than creating an application to make use of it, we’re going to interact with the database through the shell client.

If you’ve been following along so far, your container is currently running in detached mode. This means that we need to connect to it using the interactive terminal:

docker exec -it mongodb bash


The above command will connect to our deployment named mongodb using the interactive terminal and start the bash shell. More details on connecting to detached Docker containers can be found in my previous tutorial titled, Connecting to a Detached Docker Container for Terminal Interaction.

You’ll notice that you are now using your Terminal as if you were inside your container. This is where we can start using MongoDB.

To launch the MongoDB shell client, execute the following:

mongo


When inside the MongoDB shell client, you can access all the functionality that is outlined in the MongoDB documentation. For example, we can see what databases exist in our instance with the following:

show dbs


To create a new database, we can use a multi-step process, the first being to define the database we wish to use:

use thepolyglotdeveloper


We’re using the database thepolyglotdeveloper, but it doesn’t exist until we start creating collections and data. To create a collection with data, we can do something like this:

db.people.save({ firstname: "Nic", lastname: "Raboy" })
db.people.save({ firstname: "Maria", lastname: "Raboy" })


With two documents created in a new people collection in our thepolyglotdeveloper database, we can query for data using something like the following:

db.people.find({ firstname: "Nic" })


There is a lot that you can accomplish with the shell client, but you can get the general idea. What we did prove is that we were able to interact with the container instance.

Conclusion

You just saw how to download and deploy a Docker image of MongoDB as a container, then interact with it using the shell client. Docker isn’t the only way to deploy MongoDB and the shell client isn’t the only way to interact with it. These are just two of many examples on what you can accomplish.

If you want to learn more about Docker, consider enrolling in my video course titled, Containerization with Docker by Example.

A video version of this article can be seen below.

Learn More

Docker Mastery: The Complete Toolset From a Docker Captain

Learn DevOps: The Complete Kubernetes Course

Docker for the Absolute Beginner - Hands On

Docker Technologies for DevOps and Developers

Docker Swarm Mastery: DevOps Style Cluster Orchestration

The Complete Developers Guide to MongoDB

Master MongoDB, the NOSQL leader with Clarity and Confidence

MongoDB, NoSQL & Node: Mongoose, Azure & Database Management

Build a ChatApp with: (Nodejs,Socketio, Expressjs ,MongoDB)

WordPress in Docker. Part 1: Dockerization

WordPress in Docker. Part 1: Dockerization

This entry-level guide will tell you why and how to Dockerize your WordPress projects.

This entry-level guide will tell you why and how to Dockerize your WordPress projects.

List all containers in Docker(Docker command)

List all containers in Docker(Docker command)

We can get a list of all containers in docker using `docker container list` or `docker ps` commands.

We can get a list of all containers in docker using docker container list or docker ps commands.

List Docker Containers

To list down docker containers we can use below two commands

  • docker container list
  • docker ps

docker container ls command introduced in docker 1.13 version. In older versions we have to use docker ps command.

List all Containers in docker, using docker ls command

The below command returns a list of all containers in docker.

docker container list -all

or

docker container ls -all

List all containers in docker, using docker ps command

In older version of docker we can use docker ps command to list all containers in docker.

$ docker ps -all

or

$ docker ps -a

List all Running docker containers

The default docker container ls command shows all running docker containers.

$ docker container list

or

$ docker container ls

or

To get list of all running docker containers use the below command

$ docker ps

List all stopped docker containers command

To get list of all stopped containers in docker use the below commands

$ docker container list -f "status=exited"

or

$ docker container ls -f "status=exited"

or you can use docker ps command

$ docker ps -f "status=exited"

List all latest created docker containers

To list out all latest created containers in docker use the below command.

$ docker container list --latest

Show n last created docker containers

To display n last created containers in docker use the below command.

$ docker container list --last=n

Dockerize a Nodejs app connected to MongoDb

Dockerize a Nodejs app connected to MongoDb

I will run through some basic Docker terminology and concepts and then use a Node.js and MongoDB that I previously built and demonstrate how to run this in a Docker container.

Please find first part of series: 

Dockerize a Node.js app with VS Code

Problem:

You already know how to use Docker together with Node from previous article in this series. I know that we all love MERN/MEAN stacks. Our next step is to understand how Node and Mongo connects to each other running inside containers. Lets’ go!

1. Install MongoDb locally

Time to get into some document db stuff. First of all download MongoDb server from here.

If you haven’t change anything during install, it should also install a thing called MongoDb Compass Community.

This is a great tool to inspect, change, add or remove data in collections in MongoDb. You can connect to the local instance by using default address and port like on this image below or connect to any other server.

To connect locally just press connect. Inside you can see some default collections and you can play around. We will need MongoDb Compass a bit later.

2. Connect to MongoDb through Express app

In this tutorial I will be using my favorite editor Visual Studio Code. You will also need Nodejs and Docker installed. In my case I’m using Windows, so I got Docker for Windows from here.

Now run following command:

mkdir test-mongo-app && cd test-mongo-app && npm init -y && code .

Time to install dependencies. We will need express and mongoose packages.

npm i express mongoose

Create file called server.js inside root folder.

Also don’t forget to change your package.jsonto run server.js file at start.

{
 "name": "test-mongo-app",
 "version": "1.0.0",
 "description": "",
 "main": "server.js",
 "scripts": {
 "start": "node server.js"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "dependencies": {
 "express": "4.17.1",
 "mongoose": "5.6.1"
 }
}

Good. Let’s create a basic express app with two routes. One for reading Usersfrom the database and second is for adding dummy user data to it.

First of all check if everything works with just express server.

// server.js
const express = require("express");
const app = express();
const PORT = 8080;
app.get("/", (req, res) => {
 res.send("Hello from Node.js app \n");
});
app.listen(PORT, function() {
 console.log(`Listening on ${PORT}`);
});

You can run npm start to test it. If you see the message ”Listening on 8080” everything is ok. Also open http://localhost:8080 and check if you can see the hello message.

There is a nice thing called nodemon. It auto rebuilds our project when any changes happened in source code. Let’s use it! 😀

npm install — save-dev nodemon

Add a new command in package.json. So we use it for development.

 "scripts": {
 "start": "node server.js",
 "dev": "nodemon server.js"
 },

Now use run npm run dev while development instead of npm start.

npm run dev

You will notice difference in the console, because now nodemon is watching for any changes in your project and if needs, rebuild it. Change something in server.js and you will notice 😉

Now create folder src in root of the project. Here we will add all the rest files.

Let’s create a User model for mongoose. Create file names User.model.js

// User.model.js
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
 username: {
 type: String
 }
});

const User = mongoose.model("User", userSchema);

module.exports = User;

Good! Here we defined a model for our document db. User model has only one field username which is a string. Enough for now :)

Let’s add a file called connection.js for connection to the database.


// connection.js
const mongoose = require("mongoose");
const User = require("./User.model");
const connection = "mongodb://localhost:27017/mongo-test";
const connectDb = () => {
return mongoose.connect(connection);
};
module.exports = connectDb;

Please notice that mongo-test will be the name of our database (cluster)!

Now modify a bit server.js and start the app. You should see message in the console that MongoDb is connected.


// server.js
const express = require("express");
const app = express();
const connectDb = require("./src/connection");
const PORT = 8080;
app.get("/users", (req, res) => {
res.send(“Get users \n”);
});
app.get("/user-create", (req, res) => {
res.send(“User created \n”);
});
app.listen(PORT, function() {
console.log(Listening on ${PORT});
connectDb().then(() => {
console.log("MongoDb connected");
});
});

Yeah! 🎉 We connected Express app with local MongoDb instance!

3. Implement read and write to MongoDb

We should implement two routes for reading and adding new users.

Open server.js file and first of all import our model on the top:


// server.js
const User = require("./src/User.model");
// …

Then implement both routes below like this:

// server.js
app.get("/users", async (req, res) => {
const users = await User.find();
res.json(users);
});
app.get("/user-create", async (req, res) => {
const user = new User({ username: "userTest" });
await user.save().then(() => console.log(“User created”));
res.send("User created \n");
});
// …

Be attentive here we are using async/await pattern.

Basically we implemented two routes /users and /user-create. ✋ Yeah, yeah, I know that create should be done through the POST http verb but just to make testing easier and escape configuring seed method for db.

Now it’s time to test! 🔍 Open in browser this link http://localhost:8080/user-create to create a dummy user record in db. Open this link http://localhost:8080/users to get all users as JSON in browser.

After doing that you can go back to MongoDb Compass and check users collection here. You should see this

4. Dockerize Node and MongoDb

Add Docker file to the root folder.

touch Dockerfile

Paste following inside it:

FROM node:8

Create app directory

WORKDIR /usr/src/app

Install app dependencies

COPY package*.json ./

RUN npm install

Copy app source code

COPY . .

#Expose port and start application
EXPOSE 8080
CMD [ "npm", "start" ]

We can simply build our express app with this command

docker build -t mongo-app .

But.. this will only run our express app, but not together with MongoDb. That’s why we need a docker-compose file. 🐳

Now create another file called docker-compose.yml and paste this:


version: "2"
services:
web:
build: .
ports:
— "8080:8080"
depends_on:
— mongo
mongo:
image: mongo
ports:
— "27017:27017"

We defined 2 services in this file. One is our node app running on port 8080 and the other is mongodb instance.

⚠️ Before you run next command, please make sure that you changed connection string to mongo db in connection.js file.

const connection = "mongodb://mongo:27017/mongo-test";

We replaced localhost with mongo which is very important. Because we should tell the app that we want to access MongoDb from docker internal virtual network and not the local one.

Now run the magic command 🔮

docker-compose up

Open a browser on http://localhost:8080/users and http://localhost:8080/user-create to see our app running in Docker.

(In case anything doesn’t work, try to stop/remove image and containers, rebuild it by ruining docker compose-up again and if mongo image is not pulled from hub try to re-login in into docker hub or restart docker for Windows)

Thanks for reading !

🚀 If you read something interesting from that article, please like and follow me for more posts. Thank you dear codern and share it with all of your programming buddies!

Further reading

☞ Build a Basic App with Spring Boot and JPA using PostgreSQL

☞ Build a Simple CRUD App with Spring Boot and Vue.js

☞ Introducing TensorFlow.js: Machine Learning in Javascript

☞ An illustrated guide to Kubernetes Networking

☞ Google Kubernetes Engine By Example

☞ AWS DevOps: Introduction to DevOps on AWS

☞ Docker Tutorial for Beginners

☞ Kotlin Microservices With Micronaut, Spring Cloud, and JPA



Originally published on https://itnext.io