AppDividend
Latest Code Tutorials

How To Setup Node Express and MongoDB in Docker

Dockerize Node and MongoDB From Scratch

2,764

Get real time updates directly on you device, subscribe now.

In this tutorial, we will see How To Setup Node Express and MongoDB in Docker from scratch. Docker has become a standard tool not only among DevOps and Infrastructure people but also for the daily work of any developer. This article is aimed at the Docker beginners, who want to get a fully working instance of a Node Express and MongoDB app up and running in a matter of seconds for daily work. Docker will help you spin up containers (which behave like Virtual Machines but are not that heavy) and run your app on it. It gives us the ability to port the container anywhere we want on any server we want, moving from local to production gets secure and less buggy as the environment of the container which is running the app does not change.

Setup Node Express and MongoDB in Docker

We will start this tutorial by creating simple Node Express application. So let us do it.

Step 1: Install the dependencies.

Create a project folder in your main directory by the following command.

mkdir newdock

Go into the folder.

cd newdock

Install the following dependencies.

yarn add express mongodb

or

npm install express mongodb --save

I am using Yarn package manager, you can also use npm.

Step 2: Create server.js file.

First, we need to create one database file that returns the database string. So create one file db.js inside the root.

// db.js

module.exports = {
    DB: 'mongodb://mongo:27017/newdock'
}

Notice that, I have not written the localhost in the connection string. That is because we are connecting our Express application to the mongodb container. You will see later in this article.

Write the following primary express application inside a server.js file.

// server.js

const express = require('express');
const app = express();
const mongodb = require('mongodb');

const config = require('./db');
const PORT = 4000;
const client = mongodb.MongoClient;

client.connect(config.DB, function(err, db) {
    if(err) {
        console.log('database is not connected')
    }
    else {
        console.log('connected!!')
    }
});

app.get('/', function(req, res) {
    res.json({"hello": "world"});
});

app.listen(PORT, function(){
    console.log('Your node js server is running on PORT:',PORT);
});

I have created an express instance and also connect our application to the database.

Our Node application serves at Port: 4000 and when we hit the root URL(‘/’) than in response, we get the JSON data.

We have installed mongodb package that can help us to connect our app to mongodb database.

Now, our application is ready. The next step is to write the Dockerfile and docker-compose.yml file.

Step 3: Write Dockerfile inside root folder.

Inside the root folder, create a file called Dockerfile.

FROM node:7
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
CMD node server.js
EXPOSE 4000

What it does is, we will create one container called an app and that in that container, our whole project dependencies have resided. So when we deploy our container to the server, it will first install all the dependencies and then spin up the node server. The application will run on port 4000.

Step 4: Write the docker-compose.yml file.

Inside the root folder, create one file called docker-compose.yml file. Copy the following code.

version: "2"
services:
  app:
    container_name: app
    restart: always
    build: .
    ports:
      - "4000:4000"
    links:
      - mongo
  mongo:
    container_name: mongo
    image: mongo
    ports:
      - "27017:27017"

Here, we are building two containers.

  1. app container(It is our express app)
  2. mongodb container(mongodb server).

Step 5: Build the Docker containers.

Related Posts
1 of 12

If you have not installed the Docker, then please install it using this link.

Now, open the terminal in the root of the project and type the following command.

docker-compose build

It will create the containers and put our whole code inside it. It will generate step by step. Install all the dependencies and last successfully form the containers. Now, our containers are built successfully; we need to run the container.

Step 6: Run the containers.

We can up our containers using the following command.

docker-compose up

If everything is fine, you can see something like this.

Setup Node Express and MongoDB in Docker

 

Our app is running on port 4000 and we have successfully connected to the mongodb database.

Now, remember, when you need to change the file, you need to rebuild the container, and then you run. Otherwise, your latest changes will not reflect on the container.

Go to the browser and hit this URL: http://localhost:4000/

You can see that we are getting the JSON response. We have also connected our express application to the mongodb database.

Code on Github

Finally, our How To Setup Node Express and MongoDB in Docker Tutorial is over. Thanks for taking.

1 Comment
  1. Fons says

    hi Krunal,

    thanks for this tutorial!
    BUT
    i cant get it to work….
    i even cloned it. it says in my docker-terminal that its on port 4000. but…its not there on the browser.
    http://localhost:4000/
    gives me nothing.
    could there be a change somewhere? an update? im not getting any errors also. everything looks just fine. all, but the response in the browser.

    Regards, F

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.