Skip to content
Docker

4. Docker Compose Tutorial Hindi – Node.js + MongoDB

May 26, 2026 26 min read

नमस्ते दोस्तों!

स्वागत है The Easy Master पर!

तो आपने Dockerfile likhna seekh liya. एक container चलाना आ गया। Lekin ab real problem – multiple containers ek saath kaise chalayein?

Jaise aapne ek Node.js app banaya. Ab usme database chahiye – MongoDB. Ab aap kya karoge? Ek terminal mein docker run se Node.js container chalayo? Doosri terminal kholke alag se MongoDB container? Aur un dono ko manually connect karo? Network setup karo?

Been there, done that. Bohot headache hai.

Maine yeh kaam 2-3 baar manually kiya. Fir ek dost ne mujhe Docker Compose ke baare mein bataya. Ek simple docker-compose.yml file, aur ek command mein sab containers ek saath start!

In Docker Compose tutorial Hindi mein hum seekhenge:

✅ Docker Compose kya hai – beginner-friendly definition
✅ Container vs Multi-Container – scenario samjhe
✅ docker-compose.yml syntax – services, build, image, ports, depends_on, environment
✅ Node.js + MongoDB ka real project – step-by-step
✅ Networking – containers aapas mein kaise baat karein
✅ Volumes – database data persist kaise karein
✅ Environment variables – .env file se configuration
✅ Docker Compose Watch – development mein auto-reload
✅ Commands – up, down, logs, ps, exec, build
✅ Railway deploy – multi-container app online kaise daalein

Real project example se samjhenge. Practical commands likhenge. Cheat sheet milegi.

Chaliye, multiple containers ko orchestra karne ka magic seekhte hain! 🐳

Table of Contents

1. Docker Compose Kya Hai? – Multi-Container App Ka Conductor

Docker Compose ek tool hai jo multiple Docker containers ko define karne aur run karne ka kaam karta hai, using a single YAML file.

Simple words mein:
Jaise aapne Dockerfile seekha – ek container ka blueprint. Docker Compose ek YAML file hai jisme aap likhte ho ki kitne containers chalane hain, unka aapas mein connection kaise hoga, kaun si images use karni hain, ports kaise map honge, etc.

Block Analogy:

  • Docker run = Lego blocks ko manually uthake rakhna
  • Docker Compose = Lego blocks ki pre-designed map (instruction booklet) banana – jisse blocks apne aap apni jagah aa jaate hain

Docker Compose is included with Docker Desktop and is available for Linux, Windows, and Mac.

Official Definition:
“With Docker Compose, you can define all of your containers and their configurations in a single YAML file. If you include this file in your code repository, anyone that clones your repository can get up and running with a single command.”

Use cases: Docker Compose is ideal for development, testing, and staging environments and for CI/CD workflows, but it is not a production-grade orchestration tool like Kubernetes.

Default filename: compose.yaml (earlier docker-compose.yml) – both work, but compose.yaml is modern preference.

A Compose file follows the Compose Specification to define multi-container applications.

2. Multi-Container Scenario – क्यों Compose जरूरी है?

Problem bina Docker Compose ke:

  1. Frontend container (React) → docker run -p 3000:3000 frontend
  2. Backend API container (Node.js) → docker run -p 5000:5000 -e DB_URL... backend
  3. Database (MongoDB) → docker run -p 27017:27017 -v mongo_data:/data/db mongo
  4. Nginx (reverse proxy) → docker run -p 80:80 nginx

Har container ko manually run karna padega. Network set karna padega. Startup order manage karna padega.

Solution Docker Compose: Ek file mein sab define karo:

Code
services:
  frontend:
    build: ./frontend
    ports: ["3000:3000"]
  backend:
    build: ./backend
    environment:
      DB_URL: mongodb://db:27017
    depends_on: [db]
  db:
    image: mongo:latest
    volumes: [mongo_data:/data/db]

Ek command: docker compose up -d – sab containers automatically create aur start ho jayenge. Compose automatically creates a default network, so services can talk to each other using their service names.

Compose is useful for local development where the developer experiences all the benefits of a containerised environment without the overhead of managing containers and their dependencies manually.

3. Project Overview – Node.js + MongoDB App

Hum ek simple Notes App banayenge jisme:

  • User notes create, read, delete kar sakta hai
  • Data MongoDB mein store hoga
  • Node.js (Express) backend REST API provide karega

Architecture:

Code
Browser (http://localhost:3000)  →  Node.js Container (port 3000)  →  MongoDB Container (port 27017)
                                             ↓
                                        (notes stored)

This hands-on approach will show Docker Compose in action.

Setup Overview:

  1. Ek simple Node.js + Express app likhenge (CRUD APIs for notes)
  2. MongoDB connection ke liye Mongoose use karenge
  3. Dockerfile banayenge for Node.js app
  4. compose.yaml banayenge jisme Node.js aur MongoDB services define hongi
  5. Volumes se data persist karenge
  6. Environment variables se configuration manage karenge

4. Prerequisites – Pehle Se Ready Ho

Deploy karne se pehle yeh ready rakho:

✅ Docker installed – docker --version should show version
✅ Docker Compose installed – docker compose version should show version (compose v2)
✅ Node.js and npm – Local development ke liye (optional)
✅ Basic knowledge of Node.js + Express – Previous articles may help
✅ MongoDB understanding – जानते ही होंगे collections, documents
✅ Basic Docker commands – docker build, docker run

Docker Compose is included with Docker Desktop, so separate installation is not needed.

Verify Docker Compose is working:

Code
docker compose version

Expected output: Docker Compose version v5.1.0 (or later)

💡 Note: We are using docker compose (no hyphen, version 2) – the modern version. Legacy docker-compose (with hyphen) is deprecated.

Project Structure

Code
my-notes-app/
├── backend/
│   ├── Dockerfile
│   ├── package.json
│   ├── server.js
│   └── .env
├── .env
└── compose.yaml

5. Docker Compose YAML Syntax – Samjhe Easy Language Mein

Docker Compose file YAML format mein likhi jaati hai. YAML indentation sensitive hota hai – spaces ka dhyan rakho.

Basic Structure of compose.yaml

Code
services:
  service_name:           # Service name (used as hostname for networking)
    build: ./path         # Build image from Dockerfile in this path
    image: image:tag      # Or use existing image
    ports:                # Port mapping
      - "host:container"
    volumes:              # Persistent storage
      - host_path:container_path
    environment:          # Environment variables
      - KEY=VALUE
    depends_on:           # Startup order
      - other_service

Key Sections Explained

SectionPurposeExample
servicesDefines each container (app, database, etc.)services: web: db:
buildTells Compose to build image from Dockerfile in specified directorybuild: ./backend
imageUse existing image from Docker Hubimage: mongo:7
portsMap host port to container port"8080:80"
volumesPersistent storage (named volumes or bind mounts)./data:/data/db
environmentSet environment variables inside containerNODE_ENV=production
depends_onControl service startup orderdepends_on: - db

Networking – Containers Kaise Communicate Karte Hain

By default, Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by the service name.

Key points:

  • Every service gets its own container
  • Containers can reach each other using their service name as hostname
  • web service can connect to MongoDB using hostname db

Example: Your Node.js app’s MongoDB connection string: mongodb://db:27017/notes

  • db is the service name of MongoDB container in compose.yaml
  • 27017 is the port MongoDB listens on inside its container

Version Specification

Modern Docker Compose (v5.x) uses the Compose Specification directly, so you don’t need to specify a version at the top of the file. Legacy version fields (2.x, 3.x) are merged into the specification.

Always use the latest Compose Specification format for production apps.

6. Hands-On #1 – docker-compose.yml Banayein

Step 1: Node.js App Banayein

Project folder banayein:

Code
mkdir my-notes-app && cd my-notes-app
mkdir backend
cd backend

Initialize Node.js app:

Code
npm init -y

Install dependencies:

Code
npm install express mongoose
npm install -D nodemon   # for development

backend/package.json: Ensure start script is present:

Code
"scripts": {
  "start": "node server.js",
  "dev": "nodemon server.js"
}

backend/server.js – Simple Notes API:

Code
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

// MongoDB connection
const mongoURI = process.env.MONGO_URI || 'mongodb://localhost:27017/notes';
mongoose.connect(mongoURI)
  .then(() => console.log('✅ MongoDB Connected'))
  .catch(err => console.error('❌ MongoDB Error:', err));

// Note Schema
const noteSchema = new mongoose.Schema({
  title: String,
  content: String,
  createdAt: { type: Date, default: Date.now }
});
const Note = mongoose.model('Note', noteSchema);

// Routes
app.get('/notes', async (req, res) => {
  const notes = await Note.find().sort({ createdAt: -1 });
  res.json(notes);
});

app.post('/notes', async (req, res) => {
  const note = new Note({
    title: req.body.title,
    content: req.body.content
  });
  await note.save();
  res.status(201).json(note);
});

app.delete('/notes/:id', async (req, res) => {
  await Note.findByIdAndDelete(req.params.id);
  res.status(204).send();
});

app.get('/', (req, res) => {
  res.send('Notes API is running');
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

backend/Dockerfile banayein:

Dockerfile
FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --omit=dev

COPY . .

EXPOSE 3000

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

Step 2: compose.yaml Banayein

Project root (my-notes-app/) mein compose.yaml file banayein:

YAML
services:
  # Node.js Backend Service
  backend:
    build: ./backend
    ports:
      - "3000:3000"
    environment:
      - MONGO_URI=mongodb://db:27017/notes
      - PORT=3000
    depends_on:
      - db
    develop:
      watch:
        - action: sync
          path: ./backend
          target: /app
        - action: rebuild
          path: ./backend/package.json

  # MongoDB Service
  db:
    image: mongo:7
    ports:
      - "27017:27017"
    volumes:
      - mongo_data:/data/db
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: secret
    healthcheck:
      test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  mongo_data:

Step 3: Compose File Explained – Service by Service

Backend Service (our Node.js app):

FieldMeaning
build: ./backendBuild image from Dockerfile in ./backend directory
ports: "3000:3000"Map host’s 3000 port to container’s 3000 port
environment: MONGO_URI=...Set MongoDB connection string for the app. db resolves to MongoDB container
depends_on: dbStart MongoDB container before starting backend container
develop.watchEnable live code reload during development (more details later)

Database Service (MongoDB):

FieldMeaning
image: mongo:7Use official MongoDB image from Docker Hub
ports: "27017:27017"Expose MongoDB’s default port (optional, for debugging)
volumes: mongo_data:/data/dbNamed volume mongo_data stores database files – data persists even if container stops
healthcheckTest MongoDB is ready before backend starts

The MONGO_URI environment variable uses db:27017 where db is MongoDB’s service name, thanks to Compose’s internal networking.

Step 4: Run the Multi-Container App

Code
# Start all services in background
docker compose up -d

Docker Compose will:

  1. Build backend image using ./backend/Dockerfile
  2. Pull MongoDB image if not present
  3. Create network for communication
  4. Start containers in the right order (db first, then backend)

Verify running containers:

Code
docker compose ps

Check logs:

Code
docker compose logs -f

Press Ctrl+C to exit logs view.

Test the API:

Code
# GET all notes
curl http://localhost:3000/notes

# POST a new note
curl -X POST http://localhost:3000/notes \
  -H "Content-Type: application/json" \
  -d '{"title":"My First Note","content":"Hello from Docker Compose!"}'

# GET notes again
curl http://localhost:3000/notes

Step 5: Stop and Clean Up

Code
# Stop containers but keep volumes (data retained)
docker compose down

# Stop and remove containers + volumes (data deleted)
docker compose down -v

7. Hands-On #2 – depends_on aur Health Check

depends_on is helpful but it only waits for the dependent container to start, not for it to be ready. For example, depends_on: db starts MongoDB before starting backend, but MongoDB might still be initializing when backend tries to connect, resulting in connection errors.

Solution: Add a healthcheck to the database service and use depends_on with condition: service_healthy.

Our earlier compose.yaml includes a healthcheck for MongoDB. That healthcheck ensures MongoDB is ready to accept connections before backend starts.

YAML
services:
  backend:
    depends_on:
      db:
        condition: service_healthy   # Wait for db to be healthy

  db:
    healthcheck:
      test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
      interval: 10s
      timeout: 5s
      retries: 5

mongosh command is only available in MongoDB 5.0+; for older versions use mongo instead.

Using condition: service_healthy ensures your backend will only start when MongoDB is fully ready, preventing runtime connection errors.

💡 Pro Tip: For production, always use healthcheck + depends_on for services that have strict startup requirements. This eliminates “race condition” errors during container startup.

8. Hands-On #3 – Volumes se Data Persist Karein

By default, when you remove a container with docker compose down, all data inside the container is also deleted. For databases, this means losing all your data.

Two types of volumes in Docker Compose:

TypeCommandUse Case
Named Volumevolumes: mongo_data:/data/dbProduction data storage – Docker manages it
Bind Mountvolumes: ./local_dir:/app/dataDevelopment hot reload – syncs host directory

Named Volume (Production): Data is stored in Docker’s managed storage area. Best for databases, media files, etc.

Bind Mount (Development): Maps a directory from your host machine directly into the container. Any changes you make to code on your machine are instantly reflected inside the container. Ideal for development with hot reload.

Example: Development Bind Mount for Node.js

YAML
services:
  backend:
    volumes:
      - ./backend:/app          # Mount entire backend folder
      - /app/node_modules       # Exclude node_modules from mount

The second line - /app/node_modules prevents your host’s node_modules from overriding the container’s dependencies.

💡 Important: In development, use bind mounts to enable hot reload. Your local code changes will be reflected inside the container immediately, which can be convenient. Combine with nodemon to auto-restart the Node.js server on file changes.

9. Hands-On #4 – Environment Variables aur .env File

Hardcoding environment variables in compose.yaml is not secure, especially for secrets like database passwords. Use .env files.

Step 1: Create .env file in Project Root

env

Code
# .env file
MONGO_USER=admin
MONGO_PASSWORD=secret
MONGO_DB=notes
PORT=3000
NODE_ENV=development

Step 2: Reference Variables in compose.yaml

YAML
services:
  backend:
    build: ./backend
    ports:
      - "${PORT}:3000"
    environment:
      - MONGO_URI=mongodb://${MONGO_USER}:${MONGO_PASSWORD}@db:27017/${MONGO_DB}
      - NODE_ENV=${NODE_ENV}
    env_file:
      - .env   # Also loads .env into container (alternative method)

  db:
    image: mongo:7
    environment:
      - MONGO_INITDB_ROOT_USERNAME=${MONGO_USER}
      - MONGO_INITDB_ROOT_PASSWORD=${MONGO_PASSWORD}
    volumes:
      - mongo_data:/data/db

volumes:
  mongo_data:

How Variable Substitution Works

Docker Compose automatically reads from the .env file in the project directory if --env-file is not set.

You can also use multiple environment files:

Bash
docker compose --env-file .env --env-file .env.prod up

Security Best Practices:

  • Add .env to .gitignore – never commit secrets
  • Create .env.example with dummy values as a template
  • Use different .env files for different environments (.env.dev, .env.prod)

💡 Personal Experience: I once accidentally committed a .env file with production database credentials. Within hours, someone tried to access my database. Since then, I always double-check .gitignore and use secret management tools in production.

10. Docker Compose Commands – Daily Use Cheat Sheet

Here are the essential Docker Compose commands for daily use:

CommandWhat it doesExample
docker compose upStart all services (foreground)docker compose up
docker compose up -dStart all services in backgrounddocker compose up -d
docker compose downStop and remove containers, networksdocker compose down
docker compose down -vStop + remove containers, networks, and volumes (⚠️ deletes data)docker compose down -v
docker compose psList running containersdocker compose ps
docker compose logsView all service logsdocker compose logs -f
docker compose logs backendView logs for specific servicedocker compose logs -f backend
docker compose exec backend bashRun command in running containerdocker compose exec backend bash
docker compose buildRebuild images without startingdocker compose build --no-cache
docker compose up --buildRebuild images and startdocker compose up -d --build
docker compose stopStop containers without removingdocker compose stop
docker compose startStart stopped containersdocker compose start
docker compose restartRestart all servicesdocker compose restart

Complete Lifecycle Example

Code
# Start fresh
docker compose down -v     # Clean everything
docker compose up -d       # Start in background
docker compose ps          # Check status
docker compose logs -f     # Watch logs

# After code changes
docker compose build       # Rebuild images
docker compose up -d       # Restart with new images

# Shell into backend container
docker compose exec backend sh

# Inside container
ls -la
node server.js             # Test something
exit

# Stop but keep containers (for quick restart later)
docker compose stop

# Start again without rebuilding
docker compose start

# Complete cleanup when done
docker compose down -v

11. Docker Compose Watch – Development Mein Auto-Reload

Docker Compose Watch is a feature that automatically syncs local file changes to the container, enabling hot reload during development without manually rebuilding.

Configure Watch in compose.yaml

Code
services:
  backend:
    build: ./backend
    develop:
      watch:
        # Sync files to container on change
        - action: sync
          path: ./backend
          target: /app
          ignore:
            - node_modules/
        # Rebuild if dependencies change
        - action: rebuild
          path: ./backend/package.json

Run with Watch Mode

Code
docker compose watch

This command watches for file changes and:

  • Sync action: Copies changed files to the container (no rebuild needed)
  • Rebuild action: Rebuilds the entire image when critical files like package.json change

When combined with nodemon in your Node.js app, watch mode creates a seamless development experience: save a file → Docker syncs it → nodemon restarts the server → changes appear in browser instantly.

Watch vs Bind Mounts

ApproachHow it worksPerformanceUse case
Bind MountsDirect host mapping, instant syncFastDevelopment
WatchEvent-based sync, more efficientVery fastModern development

💡 Note: Compose Watch reached production-ready stability in early 2026 with Docker releases. It is now the recommended way to handle development file syncing.

12. Dockerfile vs docker-compose.yml – Difference

A common confusion: Dockerfile vs Docker Compose. Here’s the difference:

FeatureDockerfiledocker-compose.yml
PurposeBuild a single Docker imageRun and orchestrate multiple containers
FocusHow to build an imageHow to run containers together
LanguageDockerfile syntax (instructions like FROM, RUN, COPY)YAML syntax (declarative)
OutputDocker imageRunning containers (services)
Used forCreating custom images for your appDevelopment and testing multi-service apps
Commanddocker build and docker rundocker compose up

Real example analogy:

  • Dockerfile = Recipe for baking a single cake (image)
  • docker-compose.yml = Menu for a full restaurant meal (cake + coffee + music) – multiple items served together

They are complementary, not alternatives. Your project will typically have both:

  • Dockerfile defines how to build your app’s image
  • compose.yaml defines how to run your app together with databases, caches, etc.

Tip: docker compose can build images using Dockerfiles defined in build sections. It doesn’t replace Dockerfile; it automates running them together.

13. Railway Deployment – Multi-Container App Online कैसे डालें

Once your multi-container app works locally, you can deploy it to Railway.

Deploying Docker Compose Applications on Railway

Railway now supports Docker Compose directly. Here are the steps:

  1. Push your code to GitHub (make sure compose.yaml is in the root directory)
  2. Go to Railway dashboard → New Project → Deploy from GitHub
  3. Select your repository
  4. Railway automatically detects compose.yaml and deploys all services
  5. Environment variables are automatically injected

Production Considerations

For production, modify your compose.yaml:

Code
services:
  backend:
    build: ./backend
    environment:
      - NODE_ENV=production
      - MONGO_URI=${MONGO_URI}   # Use Railway-provided variable
    healthcheck:
      test: ["CMD", "node", "-e", "fetch('http://localhost:3000/health')"]
      interval: 30s
      timeout: 10s
      retries: 3

  db:
    image: mongo:7
    volumes:
      - mongo_data:/data/db   # Named volume
    healthcheck:
      test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
      interval: 30s
      timeout: 10s
      retries: 3

volumes:
  mongo_data:

Railway automatically adds environment variables like MONGO_URI when you attach a database, so you don’t need to manually manage secrets.

Railway’s internal networking resolves service names automatically. Your backend can connect to db as the hostname, just like in local development.

Note: For best production results, consider using Railway’s managed database services instead of running databases inside containers, as Railway’s managed services provide automatic backups and scaling.

14. Common Mistakes (aur Unka Solution!)

MistakeKyun Galat Hai?Solution
depends_on without healthcheckBackend tries to connect before MongoDB is ready, causing errorsAdd healthcheck to MongoDB and use condition: service_healthy in depends_on
Secrets in Compose fileAnyone with access to the file can see database passwordsUse .env files and never commit them to Git
Forgetting volumes for databasesData is lost when container is removed with docker compose downDefine named volumes for database containers
Hardcoding host ports for every servicePort conflicts on host machine when running multiple projectsLet Compose assign random ports or use different host ports per project
Not using .dockerignoreUnnecessary files (node_modules, logs) bloat build context and imageCreate .dockerignore file in the same directory as Dockerfile
Using docker compose up --build unnecessarilySlows down development (images rebuild every time)Use docker compose up for normal runs; use --build only when dependencies change
Confusing Dockerfile and compose.yamlTrying to use compose.yaml for building a single image or vice versaRemember: Dockerfile → build image; compose.yaml → run containers
Not setting resource limitsServices can consume all host resources (memory, CPU)Add deploy: resources: limits: cpus: '0.5', memory: 512M in compose.yaml
Assuming container hostnames are the same outside Compose networkContainers may not reach each other using service names if custom network is misconfiguredStick to the default network for simple setups. Let Compose create the network automatically

💡 Personal Mistake: I once spent 3 hours debugging why Node.js couldn’t connect to MongoDB. The issue was that I had defined depends_on but no healthcheck. Backend started too early, got connection refused, and crashed. After adding healthchecks, everything worked perfectly. Since then, I add healthchecks to all my database services.

15. Best Practices – Production-Ready Compose File

✅ Use specific image tags: Don’t use :latest. Use mongo:7 or mongo:8.0 for predictable behavior.
✅ Use named volumes for databases: Avoid bind mounts for database storage (performance and permission issues).
✅ Set resource limits: Prevent containers from consuming all host resources.
✅ Use healthchecks for all services that other services depend on: Ensures reliable startup.
✅ Keep secrets out of Compose files: Use .env files with .gitignore.
✅ Use depends_on with condition: service_healthy: Not just startup order, but readiness.
✅ Separate development and production Compose files: compose.yaml for dev, compose.prod.yaml for production using -f flag.
✅ Add healthcheck endpoints to your application: E.g., /health endpoint that returns 200 only when app and DB connections are healthy.
✅ Set restart policies for production: restart: unless-stopped or restart: always to keep services running.
✅ Use docker compose config to validate: Before deployment, run docker compose config to validate your compose file syntax.

Example Production-Ready compose.prod.yaml

Code
services:
  backend:
    build: ./backend
    restart: unless-stopped
    environment:
      - NODE_ENV=production
    healthcheck:
      test: ["CMD", "node", "-e", "fetch('http://localhost:3000/health')"]
      interval: 30s
      timeout: 10s
      retries: 3
    deploy:
      resources:
        limits:
          cpus: '1'
          memory: 512M

  db:
    image: mongo:7
    restart: unless-stopped
    volumes:
      - mongo_data:/data/db
    healthcheck:
      test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
      interval: 30s
      timeout: 10s
      retries: 3
    deploy:
      resources:
        limits:
          cpus: '0.5'
          memory: 1G

volumes:
  mongo_data:

16. Resources – Cheat Sheet & Practice Prompts

Essential Commands Cheat Sheet

TaskCommand
Start services (background)docker compose up -d
Stop and remove containersdocker compose down
Stop and remove containers + volumesdocker compose down -v
View container statusdocker compose ps
Watch logs (all services)docker compose logs -f
Watch logs for a specific servicedocker compose logs -f backend
Rebuild and restartdocker compose up -d --build
Execute command in running containerdocker compose exec backend bash
Stop containers (keep for restart)docker compose stop
Start stopped containersdocker compose start
Build images without startingdocker compose build
Validate compose file syntaxdocker compose config

Practice Prompts

Beginner:

  • Aapki pehli multi-container app: Ek simple Node.js app likho jo MongoDB se connect ho. compose.yaml banake docker compose up -d se run karo. docker compose ps aur docker compose logs try karo.
  • Environment variables use karo – .env file mein database password daalo aur compose file mein reference karo.

Intermediate:

  • depends_on aur healthcheck implement karo. Backend service tab tak start na ho jab tak MongoDB truly ready na ho. Health check pass hone ka wait karo.
  • Bind mounts use karke hot reload enable karo. nodemon install karo aur changes automatically restart hone chahiye bina rebuild ke.

Advanced:

  • Ek naya service add karo – Mongo Express (MongoDB web UI). Configure karo that it depends on MongoDB and uses the same network. Port map karo 8081:8081 and set environment variables.
  • Ek simple Nginx reverse proxy service add karo jo incoming requests ko Node.js backend pe route kare. Network configuration handle karo.

17. FAQ

Q1: Docker Compose aur Dockerfile mein kya antar hai?

Dockerfile ek single image build karne ke liye hai (blueprint). Docker Compose multiple containers ko orchestrate karne ke liye hai (orchestration). Aap dono ko ek saath use kar sakte ho – Dockerfile se image banao, compose.yaml se multiple containers run karo.

Q2: Kya main production mein Docker Compose use kar sakta hoon?

Yes, but only for small to medium applications. For large-scale production with high availability requirements, Kubernetes is more suitable. Docker Compose is perfect for development, staging, and small-scale production deployments.

Q3: docker compose up aur docker compose start mein kya antar hai?

up creates and starts containers (if they don’t exist). start only starts containers that have already been created (previously stopped with stop). Use up for first-time launches, start for resuming work.

Q4: Docker Compose mein environment variables kaise set karein safely?

Use .env file in the same directory as compose.yaml. Add .env to .gitignore to avoid committing secrets. Use environment section in compose.yaml to reference variables: ${MY_VARIABLE}.

Q5: Docker Compose Watch kya hota hai aur kyun use karein?

Compose Watch is a development feature that automatically syncs local file changes to the running container, enabling hot reload. It’s similar to bind mounts but more efficient. Configure it in the develop section of your compose file.

Q6: Volumes named volume aur bind mount mein kya antar hai?

Named Volume: Docker manages the storage location. Best for databases and production because data is managed properly. Bind Mount: Maps a host directory directly into container. Best for development hot reload. Use bind mounts for code, named volumes for data.

Q7: Railway par Docker Compose deploy kaise karein?

Railway supports deploying pre-built Docker images from registries. Push your code to GitHub with compose.yaml in the root directory, then deploy from GitHub on Railway. Railway automatically detects and runs your services.

Q8: Multiple projects ek saath chalane se port conflicts kaise avoid karein?

Each project gets its own network by default. Port conflicts only occur if you map the same host port in multiple projects. Solution: Use different host ports for each project, or let Compose assign random ports (remove the host port mapping and only specify container port).

Q9: Docker Compose mein logging kaise configure karein?

Add logging configuration to each service:

Code
logging:
  driver: "json-file"
  options:
    max-size: "10m"
    max-file: "3"

Q10: Dependency antara condition service_started aur service_healthy mein kya antar hai?

service_started waits only for the container to start (not ready for connections). service_healthy waits for the healthcheck to pass (container is ready). Use service_healthy for reliable startup order.

18. Conclusion – Ab Aapki Baari!

Bahut badhiya! Aapne aaj seekh liya:

✅ Docker Compose tutorial Hindi – complete beginner’s guide
✅ Multi-container scenario – kyun Compose zaroori hai
✅ compose.yaml syntax – services, ports, volumes, environment, depends_on
✅ Node.js + MongoDB ka real project – step by step implementation
✅ Networking – containers aapas mein service names se baat karte hain
✅ Volumes – named aur bind mount ke saath data persist karna
✅ Environment variables – .env file se secure configuration
✅ Health checks – ensure services are ready before dependent services start
✅ Docker Compose Watch – development mein auto-reload with live sync
✅ Commands – up, down, logs, ps, exec, build, etc.
✅ Railway deployment – multi-container app online kaise daalein

Docker Compose aapki development experience ko 10x better bana dega. Multiple containers ab manually manage nahi karne padenge – ek file, ek command, aur sab sorted.

Aapki challenge: Upar diye practice prompts mein se “intermediate” wala implement karo. Naye features try karo – healthchecks, watch mode, environment variables. Apna compose.yaml aur feedback comment mein share karo.

Next topic kya chahiye?

  • Deploying Docker Container to Cloud (AWS ECS / GCP Cloud Run)?
  • Multi-Stage Builds in Docker (Production Image Optimization)?
  • Docker Networking In-Depth (Custom Networks, Drivers)?

Comment mein batao!

The Easy Master ke saath multi-container applications seekhte raho. Happy Container Orchestration! 🐳🎼

Resources

Additional Resources

Views: 291

TheEasyMaster

Author at The Easy Master.

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *