DEV Community

Abhishek Gupta
Abhishek Gupta

Posted on • Edited on

Docker: From Zero to Production (Complete Guide for Developers)

🚧 Problem Before Docker

As a developer, you’ve probably faced this:

❌ β€œIt works on my machine, but not on yours.”

Your code runs perfectly on your system but fails on someone else’s.
It works on Windows but breaks on Linux.
It works locally but crashes in production.

πŸ‘‰ The problem is NOT your code
πŸ‘‰ The problem is the environment


🎯 Key Problems Without Docker

1. Environment Inconsistency

  • Different OS (Windows, Linux, macOS)
  • Different Node versions
  • Different configs

πŸ‘‰ Same code β†’ different results


2. β€œIt Works on My Machine”

  • Developer: βœ… works
  • Tester: ❌ broken

πŸ‘‰ Root cause: environment mismatch


3. OS Differences

  • File paths behave differently
  • System libraries vary

4. Dependency Conflicts

  • Different package versions
  • Missing libraries

πŸ‘‰ Result:

  • Crashes
  • Bugs
  • Debug hell

5. Difficult Setup

To run a project:

  • Install Node
  • Install MongoDB
  • Install RabbitMQ
  • Setup env variables

πŸ‘‰ Takes hours πŸ˜“


6. Dev vs Production Mismatch

  • Dev β†’ Windows
  • Prod β†’ Linux

πŸ‘‰ Works locally β†’ fails in production


7. Unreliable Testing

  • Bugs cannot be reproduced

8. No Standardization

  • Every developer = different setup

9. Hidden Dependencies

  • System-level libraries missing

10. Manual Setup = Error-Prone

  • Time wasted
  • Mistakes everywhere

🏒 Real Company Scenario

Imagine a team of 100+ developers:

  • Different OS
  • Different setups
  • Different tool versions

What happens?

  • ❌ Bugs cannot be reproduced
  • ❌ Developers blame testers
  • ❌ Onboarding takes days
  • ❌ Releases get delayed

πŸ“¦ What is Docker?

Docker is a tool that packages an application along with all its dependencies (like code, runtime, and libraries) into a container, so it can run consistently on any system.


🧠 Simple Understanding

πŸ‘‰ Docker creates a container (a box)
πŸ‘‰ This box has everything your app needs

πŸ‘‰ So your app:

  • Runs anywhere
  • Gives same result
  • Has no setup issues

Docker is a tool used to package and run applications in containers, ensuring they work the same across different environments.

> Docker = Package app + run anywhere without issues πŸš€
Enter fullscreen mode Exit fullscreen mode

πŸš€ What Docker Does

πŸ‘‰ Docker solves the problem by:

β€œpackaging your application along with everything that is needed needs to run your application β€”such as code, runtime, libraries, and configurationsβ€”into a container, ensuring it runs consistently across all environments.”


πŸ“¦ What Goes Inside This Box?

Docker bundles:

πŸ”Ή 1. Your Code

πŸ‘‰ Your application files

πŸ”Ή 2. Runtime

πŸ‘‰ Software needed to run your code
Examples:

  • Node.js
  • Python

πŸ”Ή 3. Libraries (Dependencies)

πŸ‘‰ All required packages
Examples:

  • npm install packages
  • pip install packages

πŸ”Ή 4. Configuration

πŸ‘‰ Settings your app needs

  • Environment variables
  • Config files

🌍 Why It Works Everywhere

πŸ‘‰ Because Docker gives:

Same environment on every system

🧠 Meaning:

  • No need to install Node
  • No need to install libraries
  • No system differences

πŸ‘‰ Everything is already inside the container

πŸ” Same Result Everywhere

πŸ‘‰ You run the container on:

  • Your laptop
  • Friend’s laptop
  • Server

πŸ‘‰ Result will be:

βœ… SAME every time

🎯 Goal of Docker

βœ… Build once, run anywhere

πŸ’‘ Birth of Docker

Docker was created to solve environment problems, not coding problems.

πŸ‘¨β€πŸ’» Creator

  • Solomon Hykes
  • Company: dotCloud
  • Year: 2013

πŸ“¦ What is a Container?

A container is a running instance of an application, which means your app is actively executing inside an isolated environment with everything it needs to work.

πŸ‘‰ A container is:

> β€œYour app + all dependencies + runtime in one package”
Enter fullscreen mode Exit fullscreen mode

Like a bag πŸŽ’:

  • Code
  • Node.js
  • Libraries
  • Config

🧠 What does β€œRunning Instance” mean?

πŸ‘‰ Running instance = Your app is currently active and working


πŸ” Break it down:

  • Instance = A copy of something

* Running = Currently working / executing

Here’s a clear, detailed, and well-structured explanation you can use πŸ‘‡


βš–οΈ Docker vs Virtual Machine

πŸ‘‰ In a Virtual Machine (VM):

  • Each VM runs a full operating system
  • It includes its own:

    • OS (Windows/Linux)
    • Kernel
    • Libraries
  • So it becomes heavy and slow


πŸ‘‰ In Docker (Containers):

  • Containers do not run a full OS
  • They share the host system’s OS kernel
  • Only include:

    • App
    • Runtime
    • Libraries

πŸ‘‰ So they are lightweight and fast

πŸ“Š Comparison Table

Feature Virtual Machine (VM) πŸ–₯️ Docker (Container) πŸ“¦
OS Full OS (separate OS for each VM) Shared OS (uses host OS)
Size Heavy (GBs) Lightweight (MBs)
Speed Slow startup Fast startup
Resource Use High (more RAM/CPU) Low (efficient use)
Boot Time Minutes Seconds
Isolation Strong (hardware level) Process-level isolation

πŸ” Deep Understanding (Simple Words)

πŸ–₯️ Virtual Machine

πŸ‘‰ Think like:

β€œRunning a computer inside another computer”

  • Needs full OS
  • Takes more memory
  • Slower

πŸ“¦ Docker

πŸ‘‰ Think like:

β€œRunning apps in separate boxes on same system”

  • No full OS needed
  • Shares system
  • Faster and efficient

πŸ” Real-Life Analogy

VM πŸ–₯️ Docker πŸ“¦
Full house 🏠 Rooms in a house 🏒

πŸ‘‰ VM = Separate house (expensive)
πŸ‘‰ Docker = Rooms in same house (efficient)

In a virtual machine, each instance runs a complete operating system, making it heavier and slower, whereas Docker containers share the host OS kernel, making them lightweight, faster, and more efficient.


⚑ One-Line Revision

VM = Full OS (heavy)
Docker = Shared OS (light & fast) πŸš€


🧠 Core Docker Concepts

🧭 1. Full Flow

Dockerfile β†’ Image β†’ Container β†’ Docker Compose
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ This is how Docker works step-by-step


πŸ”Ή 2. Dockerfile 🧾 (Starting Point)


πŸ“– Definition

Dockerfile is a set of instructions used to build a Docker image


🧠 Simple Meaning

πŸ‘‰ Dockerfile = Recipe to prepare your app


🧾 Example

FROM node:18
WORKDIR /app
COPY . .
RUN npm install
CMD ["npm", "start"]
Enter fullscreen mode Exit fullscreen mode

πŸ” Important Instructions

Instruction Purpose
FROM Base image
WORKDIR Set working folder
COPY Copy files
RUN Install dependencies
CMD Start application

πŸ§ͺ Exam Points

  • Used to build image
  • Step-by-step instructions
  • Each line creates a layer

🎯 Interview Answer

Dockerfile is a script that defines how to build a Docker image.


πŸ”Ή 3. Image 🧱 (Blueprint)


πŸ“– Definition

An Image is a read-only blueprint of your application


🧠 Simple Meaning

πŸ‘‰ Image = App setup (not running)


πŸ“¦ Contains

  • Code
  • Runtime
  • Libraries
  • Config

βš™οΈ Command

docker build -t my-app .
Enter fullscreen mode Exit fullscreen mode

πŸ” Key Points

  • Immutable
  • Reusable
  • Portable
  • Layer-based

πŸ§ͺ Exam Points

  • Static
  • Built from Dockerfile
  • Used to create containers

πŸ”Ή 4. Container πŸ“¦ (Running Instance)


πŸ“– Definition

A container is a running instance of an image, meaning an active version of your app.


🧠 Simple Meaning

πŸ‘‰ Container = App running live


πŸ“¦ Contains

  • Code
  • Runtime
  • Libraries
  • Config

βš™οΈ Lifecycle

Create β†’ Start β†’ Running β†’ Stop β†’ Remove
Enter fullscreen mode Exit fullscreen mode

πŸ”§ Commands

🧭 1. Basic Container Commands

Command Description When to Use
docker run <image> Create + start a container First time running an app
docker create <image> Create container only (not start) When you want to configure before starting
docker start <id> Start a stopped container Restart existing container
docker stop <id> Stop a running container Normal shutdown
docker restart <id> Restart container Apply quick changes
docker kill <id> Force stop container When container is stuck

πŸ“Š 2. Viewing Containers

Command Description When to Use
docker ps Show running containers Check active containers
docker ps -a Show all containers See stopped + running
docker inspect <id> Detailed info about container Debugging / deep info
docker stats Show resource usage (CPU, RAM) Monitor performance

🧹 3. Remove / Cleanup Commands

Command Description When to Use
docker rm <id> Remove a container Delete unused container
docker rm -f <id> Force remove container Remove even if running
docker container prune Remove all stopped containers Clean up system

πŸ“„ 4. Logs & Debugging

Command Description When to Use
docker logs <id> Show logs of container Check errors
docker logs -f <id> Live logs (real-time) Monitor app
docker exec -it <id> bash Access container terminal Debug inside container

βš™οΈ 5. Advanced Useful Commands

Command Description When to Use
docker attach <id> Attach to running container Interact with container
docker top <id> Show running processes Check internal processes
docker rename <old> <new> Rename container Organize containers
docker pause <id> Pause container Temporarily freeze
docker unpause <id> Resume container Continue paused container

🎯 Most Important Commands (Must Know)

docker run my-app
docker ps
docker stop <id>
docker rm <id>
docker logs <id>
docker exec -it <id> bash
Enter fullscreen mode Exit fullscreen mode

🧠 Lifecycle Mapping

Create β†’ Start β†’ Running β†’ Stop β†’ Remove
   |        |        |        |        |
 create   run     ps/logs   stop     rm
Enter fullscreen mode Exit fullscreen mode

πŸ” Key Points

  • Lightweight
  • Fast
  • Isolated
  • Temporary

πŸ”Ή 5. Docker Compose βš™οΈ (Multi-Container)


πŸ“– Definition

Docker Compose is a tool to run multiple containers together


🧠 Simple Meaning

πŸ‘‰ Used when your app has:

  • Backend
  • Database
  • Cache

πŸ‘‰ Run all with one command


🧾 Example

services:
  app:
    build: .
    container_name: commdesk-app
    ports:
      - "5000:5000"
    depends_on:
      mongo:
        condition: service_healthy
      rabbitmq:
        condition: service_healthy
    env_file:
      - .env.docker
    restart: unless-stopped
    networks:
      - commdesk-net

  mongo:
    image: mongodb/mongodb-community-server:7.0-ubuntu2204
    container_name: commdesk-mongo
    ports:
      - "27017:27017"
    volumes:
      - mongo-data:/data/db
    restart: unless-stopped
    networks:
      - commdesk-net
    healthcheck:
      test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ ping: 1 })"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s

  rabbitmq:
    image: rabbitmq:3-management
    container_name: commdesk-rabbitmq
    ports:
        - "5675:5672"
        - "15680:15672"
    environment:
      RABBITMQ_DEFAULT_USER: admin
      RABBITMQ_DEFAULT_PASS: admin
    restart: unless-stopped
    networks:
      - commdesk-net
    healthcheck:
      test: ["CMD", "rabbitmq-diagnostics", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s

volumes:
  mongo-data:

networks:
  commdesk-net:
    driver: bridge
Enter fullscreen mode Exit fullscreen mode

βš™οΈ Docker Compose Commands (Complete Table)

Title Command Description When to Use
▢️ Start Services docker-compose up Builds (if needed) and starts all services First time run or start project
▢️ Start in Background docker-compose up -d Runs services in detached mode (background) Run app without blocking terminal
πŸ”„ Rebuild & Start docker-compose up --build Rebuilds images before starting After code or Dockerfile changes
πŸ›‘ Stop Services docker-compose stop Stops running containers (does not remove) Temporarily stop app
❌ Stop & Remove docker-compose down Stops and removes containers, networks Clean shutdown / reset
πŸ” Restart Services docker-compose restart Restarts all containers Apply changes quickly
πŸ“„ View Logs docker-compose logs Shows logs from all services Debug errors
πŸ“„ Live Logs docker-compose logs -f Streams logs in real-time Monitor running app
πŸ“¦ List Containers docker-compose ps Shows running services/containers Check status
πŸ”§ Execute Command docker-compose exec <service> <cmd> Run command inside container Debug / run commands inside
πŸ”¨ Build Images docker-compose build Builds images for services Before running containers
⬇️ Pull Images docker-compose pull Downloads images from registry Get latest images
⬆️ Push Images docker-compose push Uploads images to registry Share images
πŸ“ View Config docker-compose config Shows final merged config Validate YAML
πŸ“Š Top Processes docker-compose top Shows running processes Debug performance
🧹 Remove Volumes docker-compose down -v Removes volumes with containers Full cleanup
πŸ”„ Scale Services docker-compose up --scale app=3 Runs multiple instances of a service Load testing / scaling
πŸ“› Stop Specific Service docker-compose stop <service> Stops one service only Control specific container
▢️ Start Specific Service docker-compose start <service> Starts one stopped service Restart specific service

🎯 Most Used Commands

docker-compose up -d
docker-compose down
docker-compose logs -f
docker-compose ps
docker-compose exec app bash
Enter fullscreen mode Exit fullscreen mode

⚑ Quick Understanding

  • up β†’ Start everything
  • down β†’ Stop & remove everything
  • logs β†’ Debug
  • exec β†’ Go inside container
  • build β†’ Create images

πŸ”Ή 6. .dockerignore 🚫 (Very Important)


πŸ“– Definition

.dockerignore is a file used to exclude unnecessary files from Docker image build

🧠 Simple Meaning

πŸ‘‰ Prevents unwanted files from going inside image


🧾 Example

node_modules
.git
.env
logs
Enter fullscreen mode Exit fullscreen mode

🎯 Why Use It?

  • Reduce image size
  • Faster build
  • Improve security
  • Works like .gitignore
  • Improves performance
  • Avoids unnecessary files

πŸ”— 8. Relationship (Best Explanation)

project/
β”œβ”€β”€ src/
β”œβ”€β”€ dist/
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ .dockerignore
β”œβ”€β”€ .env
β”œβ”€β”€ .env.docker
β”œβ”€β”€ package.json
β”œβ”€β”€ pnpm-lock.yaml
Enter fullscreen mode Exit fullscreen mode

🧭 1. Full Flow (Simple View)

.dockerignore β†’ Dockerfile β†’ Image β†’ Container β†’ Docker Compose
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ This is the complete journey of your app in Docker


πŸ”Ή 2. Step-by-Step (Clear Understanding)


🧾 1. Dockerfile (Start)

# -------- BUILD STAGE --------
FROM node:20-alpine AS builder

WORKDIR /app

RUN npm install -g pnpm

COPY package.json pnpm-lock.yaml ./

RUN pnpm install --frozen-lockfile

COPY . .

RUN pnpm build


# -------- PRODUCTION STAGE --------
FROM node:20-alpine

WORKDIR /app

RUN npm install -g pnpm

COPY package.json pnpm-lock.yaml ./

RUN pnpm install --prod --frozen-lockfile

COPY --from=builder /app/dist ./dist

EXPOSE 5000

CMD ["node", "dist/server.js"]
Enter fullscreen mode Exit fullscreen mode

Dockerfile = Instructions to build your app

πŸ‘‰ You define:

  • Base environment (Node, Python, etc.)
  • Install dependencies
  • Copy code
  • How to start the app

🚫 2. .dockerignore (Before Build)

node_modules
dist
.git
.env
.env.*
Dockerfile
docker-compose.yml
Enter fullscreen mode Exit fullscreen mode

.dockerignore = Ignore unnecessary files

πŸ‘‰ Docker skips files like:

  • node_modules
  • .git
  • .env

🎯 Why?

  • Smaller image
  • Faster build
  • Better security

🧱 3. Image (Build Stage)

Image = Ready setup of your app (not running)

πŸ‘‰ Built using:

docker build -t my-app .
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Contains:

  • Code
  • Runtime
  • Libraries
  • Config

πŸ“¦ 4. Container (Run Stage)

Container = Running instance of image

πŸ‘‰ Run using:

docker run my-app
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Now your app is:

  • Live
  • Working
  • Handling requests

βš™οΈ 5. Docker Compose (Multi-Container)

Docker Compose = Run multiple containers together

πŸ‘‰ Used when app has:

  • Backend
  • Database
  • Cache

πŸ‘‰ Run everything:

docker-compose up
Enter fullscreen mode Exit fullscreen mode

πŸ”— 3. How They Connect (Core Logic)


πŸ”„ Flow Logic

  • Dockerfile β†’ defines setup
  • Image β†’ stores setup
  • Container β†’ runs setup
  • Docker Compose β†’ manages multiple containers
  • .dockerignore β†’ optimizes build

πŸ” 4. Real-Life Analogy (Best)

Concept Example
Dockerfile Recipe πŸ“–
.dockerignore Remove bad items ❌
Image Prepared ingredients πŸ₯—
Container Cooking food 🍳
Docker Compose Full meal 🍽️

🎯 5. Interview Answer (Perfect)

Dockerfile defines how to build an image, the image is a blueprint of the application, and when executed it creates a container which runs the application. Docker Compose is used to manage multiple containers, and .dockerignore is used to exclude unnecessary files during the build process.


⚑ 6. Quick Revision

πŸ‘‰ Dockerfile β†’ Build
πŸ‘‰ Image β†’ Setup
πŸ‘‰ Container β†’ Run

πŸ‘‰ Docker Compose β†’ Multi-container
πŸ‘‰ .dockerignore β†’ Optimization

> Dockerfile β†’ Image β†’ Container
> Docker Compose β†’ manage multiple containers
> .dockerignore β†’ optimize build πŸš€
Enter fullscreen mode Exit fullscreen mode

πŸ—οΈ Real Project Setup (Node + Mongo + RabbitMQ)

πŸ” Environment Strategy (CRITICAL)

.env (Local)

MONGO_URI=mongodb://localhost:27017/CommDesk
RABBITMQ_URL=amqp://admin:admin@localhost:5672
Enter fullscreen mode Exit fullscreen mode

.env.docker

PORT=5000
NODE_ENV=development

MONGO_URI=mongodb://mongo:27017/CommDesk
RABBITMQ_URL=amqp://admin:admin@rabbitmq:5672

JWT_SECRET=your_JWT

SMTP_USER=
SMTP_PASS=

DOCKER=true
Enter fullscreen mode Exit fullscreen mode

🐳 Dockerfile (pnpm + Production Ready)


🚫 .dockerignore



🌐 Networking Magic

Inside Docker:

Service Hostname
Mongo mongo
RabbitMQ rabbitmq

πŸ‘‰ That’s why:

mongodb://mongo:27017
Enter fullscreen mode Exit fullscreen mode

works


βš™οΈ Node Config (IMPORTANT)

import { config } from "dotenv";

if (!process.env.DOCKER) {
  config();
}
Enter fullscreen mode Exit fullscreen mode

▢️ Run Everything

First time

docker compose up --build
Enter fullscreen mode Exit fullscreen mode

Background

docker compose up -d
Enter fullscreen mode Exit fullscreen mode

Stop

docker compose down
Enter fullscreen mode Exit fullscreen mode

πŸ” Debugging

docker compose logs -f app
docker exec -it commdesk-app sh
printenv
Enter fullscreen mode Exit fullscreen mode

🐰 RabbitMQ UI

http://localhost:15672
admin / admin
Enter fullscreen mode Exit fullscreen mode

⚑ Common Errors

❌ ENOTFOUND mongo

πŸ‘‰ Using docker run

❌ ECONNREFUSED

πŸ‘‰ Service not ready


πŸ”₯ Next Level (Monster Upgrades)

  • Hot reload with volumes
  • Nginx reverse proxy
  • CI/CD pipeline
  • Kubernetes
  • Microservices architecture

🧠 Final Architecture

Client β†’ Node App (Docker)
           ↓
    MongoDB + RabbitMQ
Enter fullscreen mode Exit fullscreen mode

🏁 Final Command

docker compose up --build
Enter fullscreen mode Exit fullscreen mode

🎯 Final Takeaway

Docker solves the biggest problem in development:

❌ Environment inconsistency
βœ… Consistent, portable, reliable apps

Top comments (0)