Sling Academy
Home/Node.js/Node.js with Docker Compose, Express, Mongoose, and MongoDB

Node.js with Docker Compose, Express, Mongoose, and MongoDB

Last updated: December 29, 2023

Introduction

Containerization is a powerful strategy for developing applications in a way that enhances portability and scaling. Docker is a prevalent tool for containerization, and when combined with Docker Compose, it allows for defining and running multi-container Docker applications with ease. In this guide, we’ll walk through setting up a Node.js application with Express, Mongoose, and MongoDB using Docker and Docker Compose. This setup provides a robust and reproducible environment for development and deployment.

Prepare your environment

Before you begin, make sure you have Docker and Docker Compose installed on your system. You can download them from the official Docker website.

The Steps

Create Node.js Application

Start by creating a new directory for your project and initialise a Node.js application using npm:

mkdir myapp
 cd myapp
 npm init -y

Add Express and Mongoose as dependencies:

npm install express mongoose

Set up an Express App

Create an ‘app.js’ file that sets up a basic Express server:

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

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Prepare Docker Environment

Next, create a ‘Dockerfile’ in the project root that sets up a Docker image for Node.js application:

FROM node:14

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD [ "node", "app.js" ]

Create a ‘.dockerignore’ file to exclude certain files from the Docker context, specifically node_modules, which should not be included in the Docker image, and other unnecessary files:

node_modules
npm-debug.log

Define Docker Compose Services

In the root of your project, create a ‘docker-compose.yml’ file that defines the services (Node.js and MongoDB) and their configuration:

version: '3.8'
services:
  app:
    container_name: node_app
    restart: always
    build: .
    ports:
      - '3000:3000'
    links:
      - mongo
    environment:
      - MONGO_URI=mongodb://mongo:27017/myapp
  mongo:
    container_name: mongo
    image: mongo
    ports:
      - '27017:27017'

Run Docker compose

Now you can start your services:

docker-compose up -d

To shut down the services and clean up:

docker-compose down

The Final Code

Below is the complete setup of the project, with every aforementioned file showing essential input.

app.js:

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

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Running on ${PORT}`); 
});

Dockerfile:

FROM node:14
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
 EXPOSE 3000
 CMD [ "node", "app.js" ]

docker-compose.yml:

version: '3.8'
services:
  app:
    container_name: node_app
    restart: always
    build: .
    ports:
      - '3000:3000'
    links:
      - mongo
    environment:
      - MONGO_URI=mongodb://mongo:27017/myapp
  mongo:
    container_name: mongo
    image: mongo
    ports:
      - '27017:27017'

Conclusion

After following this guide, you should have a Node.js application running inside a Docker container, all networked with MongoDB also running in a separate Docker container handled by Docker Compose for inter-service communication. This provides a very reproducible development and deployment stack, and leverages the benefits of containerization and orchestration. With this setup, you can further expand and mature your Node.js applications to fit your custom requirements efficiently and reliably.

Next Article: How to Setup a Node.js Cluster for Speed & Stability

Previous Article: Setting Up Docker Compose with Node.js, Express, Sequelize, and MySQL

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates