How to Setup Node Express and MongoDB in Docker

Here is the step-by-step guide to setting up node express and MongoDB in Docker.

Step 1: Install the dependencies.

Create a project folder in your leading 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 the Yarn package manager, and you can also use npm.

Step 2: Create a 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 this 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 connected our application to the database.

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

We have installed a mongodb package to help us connect our app to the 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 the 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 in that container, our whole project dependencies reside. 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.

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

Now, open the terminal at the project’s root and type the following command.

docker-compose build

It will create the containers and put our whole code inside them. Then, it will generate step by step. Finally, install all the dependencies and successfully build the containers. Now our containers are constructed 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 runs on port 4000, and we have successfully connected to the mongodb database.

Remember, when you need to change the file, you need to rebuild the container and 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

That’s it for this tutorial. Thanks for taking it.

15 thoughts on “How to Setup Node Express and MongoDB in Docker”

  1. 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

    Reply
  2. 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 172.18.0.2:27017]”

    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

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

      Reply
      • 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?

        Reply
          • – remove containers
            – make sure the mongo uri uses the container name found in the compose file
            – lock down a specific mongo version for example 3.6.13

            do a docker-compose build to create the containers first, then docker-compose up

            Before I was using docker-compose up –build which should rebuild each time but if your mongo container if not running in the first place because of some error you can see how this won’t work

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

    Reply
  4. – remove containers
    – make sure the mongo uri uses the container name found in the compose file
    – lock down a specific mongo version for example 3.6.13

    do a docker-compose build to create the containers first, then docker-compose up

    Before I was using docker-compose up –build which should rebuild each time but if your mongo container if not running in the first place because of some error you can see how this won’t work

    Reply
  5. Thank you for the tutorial. I am new to Docker, Mongo. I receive the following error when I type ‘docker-compose build’ in the terminal:

    ERROR: Service ‘app’ failed to build : COPY failed: stat /var/lib/docker/tmp/docker-builder539072260/package.json: no such file or directory

    In the tutorial, there is no mention of the creation of a package.json file, thus how could we ‘copy’ it. I understand the package.json file should include descriptions as well as dependencies…can someone clarify:

    1) should I create the package.json file in the project root directory
    2) what should the contents of the package.json file include?

    Thank you.

    Reply

Leave a Comment

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