Latest Code Tutorials

How To Setup Node Express and MongoDB in Docker

Dockerize Node and MongoDB From Scratch


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.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

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


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 {

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
COPY package.json /app
RUN npm install
COPY . /app
CMD node server.js

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"
    container_name: app
    restart: always
    build: .
      - "4000:4000"
      - mongo
    container_name: mongo
    image: mongo
      - "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.

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. Fons says

    hi Krunal,

    thanks for this tutorial!
    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.
    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

  2. federico says

    Hi Krunal,

    I always receive the message “database is not connected”, looging the err in the callback this is the message
    “MongoNetworkError: failed to connect to server [mongo:27017] on first connect [MongoNetworkError: connect ECONNREFUSED]”

    But if i try to connect to the mongo instance with another software it is up and running.
    Any Idea what I can try?

    Thanks for the tutorial

    1. xiaojun says

      Have you solved the problem? If yes, please tell me how to solve it.

    2. Nitin Bodhane says

      In node application, Change mongodb path to “mongodb://mongo:27017/database_name” and also make sure your mongodb container name should be “mongo”

      1. sai says

        In my node application, i have the path as “mongodb://mongo:27017/database_name” and also the the container name is mongo. But still i couldn’t connect to mongo in docker. Any idea why?

  3. xiaojun says

    Have you solved the problem? If yes, please tell me how to solve it.

  4. xiaojun says

    Have you solved the problem? If yes, please tell me how to solve it.

  5. Rahil says

    Good Article, it’s always best to have separate containers for application and database and have them run using docker-compose.

Leave A Reply

Your email address will not be published.

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