Skip to main content
In this lesson, we explore an application architecture that leverages multiple containers to separate concerns effectively. The architecture consists of two containers:
  • An API container running a Node.js/Express application.
  • A MongoDB container using the default Mongo image.
This setup demonstrates how to configure inter-container communication using Docker Compose and how the API leverages environment variables to configure its connection to MongoDB.
The Node.js application integrates with MongoDB through Mongoose and implements a basic CRUD interface to manage notes.

Docker Compose Configuration

Below is an example Docker Compose configuration outlining the multi-container deployment. Two variants for the MongoDB volume configuration are provided based on your persistence needs.

API Container Setup

The API container is built from the project source and exposes port 3000. It uses environment variables for connecting to the MongoDB container, as illustrated by the following excerpt:

Console Output Example

A sample console output upon running the application might appear as follows:

Docker Compose Variants

Variant 1 – Using a Bind Mount

This variant uses a bind mount for the MongoDB data directory to link the container’s /data/db to a local folder.

Variant 2 – Using a Named Volume

This variant uses a named volume (mongo_data) to manage the persistence of MongoDB data.
Ensure that the environment variables for MongoDB (MONGO_USER, MONGO_PASSWORD, MONGO_IP, and MONGO_PORT) are correctly passed to the API container. This is crucial for establishing a successful connection.

API Endpoints

The API provides a set of endpoints for performing CRUD operations on a “notes” collection. Below are details of each endpoint with corresponding code examples.

GET /notes

Retrieves all notes stored in the database.

GET /notes/:id

Retrieves the details of a single note based on the provided ID. (The relevant code for this endpoint is implied by the overall CRUD structure.)

POST /notes

Creates a new note entry in the database.

PATCH /notes/:id

Updates an existing note and returns the updated note if successful.

DELETE /notes/:id

Deletes a note corresponding to a given ID.
A sample console output after executing these operations might be:

Connecting to MongoDB

The application uses Mongoose to establish a connection with the MongoDB container at startup. The connection relies on the environment variables defined earlier. Once the connection is successful, the server begins listening on port 3000.
Make sure your environment variables for the MongoDB connection are properly set in your deployment configuration to avoid connectivity issues.
Transcribed by Otter.ai

Watch Video