Site icon RemoteStack

How to Connect Node Express with MongoDB in Docker

Set up Docker in Node Express and MongoDB tutorial; In this tutorial, we will teach you how to set up Docker in the Node js application. We will also enlighten on setting up Docker with express js and MongoDB database in Node js environment.

Docker is a powerful open-source containerization platform. It facilitates web developers to package applications into containers.

It was founded based on the idea that you can package your application code with dependencies into a deployable unit called a container.

Due to its flexible ecosystem, it is getting popular among developers. It standardized their day-to-day coding work. If you work with Node and are just getting started with Docker, then this quick guide is for you.

Docker makes developers’ lifeless cumbersome; it works the same as Virtual Machines. It consumes less memory and allows you to run your application without any hassle. Docker is a great tool. However, it also has certain advantages and disadvantages. In this tutorial, we are going to talk about the good points.

The good thing about Docker is you can use various ports for various containers and connect with any server. Not just that, it is also very easy to relocate the app from the local system to the production.

How to Integrate Docker in Node Js, Express with MongoDB

Set Up Node Project

Use the given command to manifest a new blank folder on your system.

mkdir node-docker-app

Now, you have to enter into the project folder:

cd node-docker-app

You need to have a package.json file, you can create it using the given command.

npm init

Let us create the node server file, hence create app.js file at the project root. Then, register it inside the package.json file.

{
  "main": "app.js",
}

Install Essential Modules

In this step, we will be using the given command to install the express and mongoDB packages.

npm install express mongodb

Configure MongoDB Connection

In your project directory, create the database.js file, this file holds the mongo database connection.

Make sure to add the code in the database.js file.

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

Build Node Server File

Previously, we created the app.js file. Now, in this step you have to open that file and insert the following code to configure the node server.

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

const app = express()

const db = require('./database')

const PORT = 3000

const mdbClient = mongodb.MongoClient

mdbClient.connect(db.DB, function (err, db) {
  if (err) {
    console.log('Error occurred while connecting to database.')
  } else {
    console.log('Database successfully connected!!')
  }
})

app.get('/', function (req, res) {
  res.json({ name: 'John Doe' })
})

app.listen(PORT, function () {
  console.log('Node app connected on:', PORT)
})

Set Up Docker File

In order to create a Docker container, we require a Dockerfile. Basically, it is a read-only file, which contains a set of instructions, make sure to create Dockerfile and insert the given code into it.

FROM node
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
CMD node app.js
EXPOSE 3000

We are using the docker build command. It builds Docker images from a Dockerfile that refers to a particular context. Basically, a set of files located in the specified PATH.

docker build -t node-docker .

Again, open the terminal and execute the docker run command:

docker run -t -p 3000:3000 node-docker

We have mentioned two ports, one port refers to node app port another refers to docker container port.

If you somehow get “port is already allocated. ERRO[0003] error waiting for container: context canceled” error, make sure to follow given instructions.

docker container ls

docker rm -f <container-name>

Make Docker Compose File

The Compose file is a YAML file consists services, networks, and volumes for a Docker application.

Next, you have to create the docker-compose.yml file, ensure that you copy all the code, and place it into the file.

With the help of the docker-compose file, we evoked two containers simultaneously, the express app container and the MongoDB server container.

version: "3"
services:
  web:
    image: node-docker
    build: .
    command: "node app.js"
    ports:
      - "3000:3000"
    depends_on:
      - "mongo"
  mongo:
    image: "mongo"
    ports:
      - "27017:27017"

Create Docker Container

This step will demystify how to create a docker container for node application; we assume you have already installed the Docker app on your system.

If, anyhow, you haven’t installed the app, make sure to visit docker website.

Go ahead and open the terminal, insert the given command on the command prompt, and hit enter.

docker-compose build

Invoke Docker Container

The previous command invokes the two containers containing the entire code within itself, which is the usual way of forming the containers.

We can now run the containers using the given command.

docker-compose up

Here is the url on which you can check the Node js and Express Js Docker app.

 http://localhost:3000

On which your app is working, and mongo db is successfully connected. If you make any changes in the file, you have to reconstruct the container and run it again.

Summary

In this tutorial, we have learned how to connect docker with Node js application in conjunction with MongoDB and Express js. We cover setting up a docker container for a node js application. Most importantly saw how to run the docker container in a Node js environment.

Exit mobile version