DEV Community

Ankit Kumar
Ankit Kumar

Posted on

Ultimate Guide to Containerizing Node.js + MongoDB

Ankit | Jr DevOps Engineer | akv280501@gmail.com

πŸ“ File Breakdown & Architecture

1. docker-compose.yml

Purpose: Defines multi-container architecture

version: '3.8'

services:
  app:
    build: .
    container_name: node_app
    ports:
      - "3000:3000"
    environment:
      - DB_URI=mongodb://mongo:27017/testdb
    depends_on:
      - mongo


  mongo:
    image: mongo:latest
    container_name: mongo_db
    ports:
      - "27017:27017"
    volumes:
      - mongodata:/data/db

volumes:
   mongodata:

Enter fullscreen mode Exit fullscreen mode

Key Concepts:

  • Service Discovery: Containers communicate via service names (mongo)

  • Port Mapping: 3000:3000 exposes Node.js to host machine

  • Declarative Setup: Infrastructure-as-Code

2. Dockerfile

Layer-by-Layer Optimization:

FROM node:18-alpine

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD ["npm", "start"]

Enter fullscreen mode Exit fullscreen mode

Best Practices:

  • Layer Caching: Separate COPY package.json + RUN npm install speeds up rebuilds

  • Minimal Images: Alpine reduces attack surface

  • Explicit Ports: Documentation for other developers

3. package.json

Dependency Management:

{
  "name": "node-mongo-app",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.18.2",
    "mongoose": "^7.4.3"
  }
}

Enter fullscreen mode Exit fullscreen mode

Why It Matters:

npm start becomes the container's PID 1 process

Version pinning (^4.18.2) prevents breaking changes

4. server.js

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

const app = express();
const PORT = 3000;

// Connect to MongoDB -> 'mongodb://mongo:27017/testdb'
// 'mongo' is the service name we will use in docker-compose
const dbUri = process.env.DB_URI || 'mongodb://localhost:27017/testdb';
mongoose.connect(dbUri)
    .then(() => console.log('MongoDB connected successfully!'))
    .catch(err => console.error('MongoDB connection error:', err));

app.get('/', (req, res) => {
    res.send('Hello from your Node.js app! Connected to MongoDB.');
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Enter fullscreen mode Exit fullscreen mode

πŸš€ My DevOps Learning Path

20 Projects Challenge:

  1. βœ… Node+MongoDB Containers

  2. Flask+Redis+PostgreSQL (Coming Soon)

πŸ’¬ Let's Build Together!

I need your input on:

*Which project should I tackle next?

*How would you improve this setup?

*DevOps interview tips for 2-3 yr experience roles

Hire Me:

πŸ“ž +91-8384860549 | πŸ“§ akv280501@gmail.com
Open to relocation | Immediate joiner

DevOps #Docker #Mentorship #Hiring

Top comments (0)