Multi-Container Application
Now let's put everything together by building a complete multi‑container application using Docker Compose. We'll create a simple web app with a Node.js frontend, a MongoDB database, and a volume for persistent data.
Application Overview
We'll build a simple todo app where users can add tasks. The stack:
- Node.js: REST API that connects to MongoDB.
- MongoDB: NoSQL database.
- Volume: To persist MongoDB data.
Step 1: Create the Node.js App
Create a folder
todo-app with a subfolder app. Inside app, create package.json and server.js.package.json (minimal):
{
"name": "todo-app",
"version": "1.0.0",
"dependencies": {
"express": "^4.18.2",
"mongoose": "^7.0.0"
}
}server.js:const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
mongoose.connect('mongodb://db:27017/todo', { useNewUrlParser: true });
const Task = mongoose.model('Task', { name: String });
app.get('/tasks', async (req, res) => {
const tasks = await Task.find();
res.json(tasks);
});
app.post('/tasks', async (req, res) => {
const task = new Task({ name: req.body.name });
await task.save();
res.json(task);
});
app.listen(3000, () => console.log('Server running on port 3000'));Step 2: Create a Dockerfile for Node.js
Inside
app, create Dockerfile:FROM node:18-alpine
WORKDIR /app
COPY package*.json .
RUN npm install
COPY . .
CMD ["node", "server.js"]Step 3: Write docker-compose.yml
In the root (
todo-app), create docker-compose.yml:services:
app:
build: ./app
ports:
- "3000:3000"
environment:
- NODE_ENV=development
depends_on:
- db
db:
image: mongo:latest
volumes:
- mongo-data:/data/db
volumes:
mongo-data:Step 4: Run the Application
Navigate to the
todo-app folder and run:docker compose up --build -dCheck the logs:docker compose logs -f appYour API is available at http://localhost:3000/tasks. You can test with curl or Postman.Testing the API
Add a task:
curl -X POST http://localhost:3000/tasks -H "Content-Type: application/json" -d '{"name":"Learn Docker"}'List tasks:curl http://localhost:3000/tasksCleanup
To stop and remove everything including the volume:
docker compose down -vTwo Minute Drill
- Use Compose to combine a Node.js app, MongoDB, and a volume.
- Service names are used as hostnames (e.g.,
db). - Build the app image with
build: ./appand run withdocker compose up --build. - Persist database data using a named volume.
- Test the API with curl or a browser.
Need more clarification?
Drop us an email at career@quipoinfotech.com
