This article explores multi-container application architecture using Docker Compose to configure an API and MongoDB container for effective inter-container communication.
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.
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.
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:
Copy
Ask AI
const express = require("express");const mongoose = require("mongoose");const cors = require("cors");const Note = require("./models/noteModel");const app = express();app.use(cors());app.use(express.json());const mongoURL = `mongodb://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@${process.env.MONGO_IP}:${process.env.MONGO_PORT}/?authSource=admin`;// Alternative connection string for local testing:// const mongoURL = `mongodb://localhost:27017/?authSource=admin`;
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.
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.
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.
Copy
Ask AI
mongoose .connect(mongoURL, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => { console.log("Successfully connected to DB"); app.listen(3000, () => console.log("Server is listening on PORT 3000") ); }) .catch((e) => { console.log(e); process.exit(1); });
Make sure your environment variables for the MongoDB connection are properly set in your deployment configuration to avoid connectivity issues.