A Beginner's Guide to Docker: From Basics to MongoDB Deployment
Introduction
Docker simplifies application deployment by packaging applications and their dependencies into lightweight, portable containers. This guide will help you get started with Docker, walk you through essential commands, and demonstrate how to use Docker Compose to manage multi-container applications effectively.
What is Docker?
Docker is a platform that enables you to package and run applications in isolated environments called containers. These containers are lightweight and include everything needed to run your application — code, runtime, system tools, libraries, and settings.
Getting Started
Installation
Download Docker Desktop for your operating system (Mac, Linux, or Windows)
Follow the installation instructions for your platform
Basic Docker Concepts
Images
Definition
A Docker image is a lightweight, standalone, executable package that contains everything needed to run an application, including the code, runtime, libraries, and system tools.
Key Features
Blueprint for Containers: Images serve as the blueprint from which containers are created. Each image can be used to instantiate multiple containers.
Immutable: Once created, images cannot be changed. This immutability ensures consistency across deployments.
Layered Structure: Images are built in layers, allowing for efficient storage and reuse of common components. Each instruction in a Dockerfile creates a new layer.
Can be Pulled or Built: Images can either be pulled from Docker Hub or built locally using a Dockerfile.
Common Commands
- Build an Image:
docker build -t <image_name> .
. List Local Images:
docker images
#or
docker image ls
- Delete an Image:
docker rmi <image_name>
Containers
Definition
A container is a running instance of a Docker image. It encapsulates the application and its dependencies in an isolated environment.
Key Features
Runtime Instance: Containers are live instances that execute the application defined in the image. They can be started, stopped, and removed.
Isolation: Containers provide isolation from the host(maybe your laptop/desktop/server) system and other containers, ensuring that applications run uniformly regardless of the environment.
Consistent Environment: Since containers run the same way on any infrastructure, they eliminate issues related to environment differences between development and production.
Lightweight: Containers share the host OS kernel but operate independently, making them more resource-efficient compared to traditional virtual machines.
Containers do not run a full OS. They run only the processes defined in the image, using the minimal components required by the application.
When you run a Docker image, it creates a container. The container shares the host OS kernel but uses the OS filesystem from the image (like Alpine Linux). The OS can be of 4 types :
1. Alpine-like Lightweight OS:
Examples: Alpine Linux, BusyBox
Characteristics:
Extremely small size (e.g., Alpine is ~5 MB).
Minimalistic, designed specifically for security and efficiency.
Includes only the most essential libraries and tools.
Commonly used in Docker for lightweight containers.
Use Case:
- Ideal for microservices, minimal applications, or environments where every megabyte counts.
2. General-Purpose OS:
- Examples: Ubuntu, Debian, CentOS, Fedora
Characteristics:
Larger size compared to lightweight OS (e.g., Ubuntu ~29 MB for minimal version).
Includes a more comprehensive set of tools, libraries, and utilities.
Easier to work with for developers used to traditional Linux environments.
Use Case:
For applications requiring more libraries or tools out of the box.
Easier compatibility with complex dependencies.
3. Windows OS:
Examples: Windows Server Core, Windows Nano Server
Characteristics:
Used for Docker containers running Windows-based applications.
Heavier compared to Linux-based images.
Docker supports Windows containers natively on Windows hosts.
Use Case:
- Applications specifically built for Windows environments (e.g., ASP.NET, IIS).
4. Scratch (Bare Minimum):
Example: scratch
(technically not an OS)
Characteristics:
No base OS at all.
Only includes the application and its absolute dependencies.
The smallest possible container size.
Use Case:
Extremely performance-critical applications.
Typically for statically compiled binaries (e.g., written in Go or Rust).
5. Security-Focused OS:
Examples: Distroless (Google’s Distroless images), Red Hat UBI Minimal
Characteristics:
Focus on security by removing package managers and other tools that aren’t needed in production.
Reduces the attack surface of containers.
Use Case:
Production environments where security and stability are critical.
#For ex:
docker pull mongo-express:1.0.2-20-alpine3.19
Common Commands
- Create and Run a Container:
docker run --name <container_name> <image_name>
- Run a Container in the Background:
docker run -d <image_name>
- List Running Containers:
docker ps
#for all(along with stopped containers)
docker ps -a
- Remove a Stopped Container:
docker rm <container_name>
Volumes
Definition
A volume is a persistent storage mechanism in Docker that allows data to be stored outside of the container’s filesystem.
Key Features
Data Persistence: Volumes enable data to persist even when containers are stopped or removed. This is crucial for databases and applications that require data retention.
Shared Access: Multiple containers can share the same volume, allowing them to access and modify the same data concurrently.
Isolation from Container Lifecycle: Unlike container filesystems, volumes are not tied to the lifecycle of a specific container. They can be created, managed, and deleted independently.
Performance Benefits: Using volumes can improve performance for I/O operations compared to using the container’s writable layer.
Creating and Managing Volumes
- Create a Volume:
docker volume create <volume_name>
- List Volumes:
docker volume ls
- Remove a Volume:
docker volume rm <volume_name>
Builds
Definition
Building an image in Docker refers to the process of creating a Docker image from a set of instructions defined in a Dockerfile.
Key Features
Dockerfile as Blueprint: A Dockerfile contains all the commands needed to assemble an image. It specifies the base image, application code, dependencies, and configurations.
Layered Architecture: Each command in a Dockerfile creates a new layer in the image. This allows for efficient caching and reuse of layers, speeding up subsequent builds.
Customizability: Users can customize their images by specifying environment variables, copying files, and running commands during the build process.
Building an Image
- Basic Build Command:
docker build -t <image_name> .
- Build Without Cache:
docker build -t <image_name> . --no-cache
Essential Docker Commands
Image Management
# List all local images
docker images
# Pull an image from Docker Hub
docker pull <image_name># Remove an image
docker rmi <image_name># Remove unused images
docker image prune
Container Operations
# Run a container
docker run --name <container_name> <image_name>
# List running containers
docker ps# List all containers (including stopped)
docker ps --all# Stop a container
docker stop <container_name># Remove a container
docker rm <container_name># View container logs
docker logs -f <container_name># Access container shell
docker exec -it <container_name> sh
Practical Example: MongoDB Deployment
Method 1: Simple MongoDB Container
# Run MongoDB with custom port
docker run --name my-mongo-two -p 4001:27017 -d mongo
This command:
Creates a container named “my-mongo-two”
Maps (-p is for PORT) port 4001 on host to MongoDB’s default port (27017)
Runs in detached mode (-d)
Method 2: MongoDB with Authentication
docker run -p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=root \
-e MONGO_INITDB_ROOT_PASSWORD=example \
--name mongo-one \
--network mongo-network \
-d mongo
Method 3: MongoDB with Mongo Express
docker run --network mongo-network \
--name mongo-express \
-p 8081:8081 \
-e ME_CONFIG_MONGODB_SERVER="mongo-one" \
-e ME_CONFIG_MONGODB_ADMINUSERNAME="root" \
-e ME_CONFIG_MONGODB_ADMINPASSWORD="example" \
-e ME_CONFIG_BASICAUTH_USERNAME="example" \
-e ME_CONFIG_BASICAUTH_PASSWORD="example" \
-d mongo-express
Docker Compose: Simplified Deployment
Docker Compose allows you to define and run multi-container applications. Here’s how to set up MongoDB and Mongo Express using Docker Compose:
version: '3'
services:
mongo-one:
image: mongo
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
volumes:
- mymongo-data:/data/db
mongo-express:
image: mongo-express
restart: always
ports:
- "8081:8081"
environment:
ME_CONFIG_MONGODB_SERVER: mongo-one
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: example
ME_CONFIG_BASICAUTH_USERNAME: example
ME_CONFIG_BASICAUTH_PASSWORD: example
volumes:
mymongo-data:
driver: local
Save this as docker-compose.yml
and run:
# docker-compose up -d (optional)
#-d for detach mode
docker-compose docker-compose.yml up
Creating and Publishing Your Own Docker Image
Let’s create a simple Node.js application and dockerize it:
- Create a simple Node.js application:
// app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Docker!');
});
app.listen(3000, () => {
console.log('App running on port 3000');
});
- Create a Dockerfile:
FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
- Build the image:
docker build -t your-username/node-hello-world .
- Test locally:
docker run -p 3000:3000 your-username/node-hello-world
- Publish to Docker Hub:
# Login to Docker Hub
docker login
# Push the image
docker push your-username/node-hello-world
Best Practices
Always use specific tags for base images
Minimize the number of layers in your Dockerfile
Use .dockerignore to exclude unnecessary files
Clean up unused images and containers regularly
Use Docker Compose for multi-container applications
Always set resource limits for containers in production
Never store sensitive information in images
Additional Resources
Docker Documentation: https://docs.docker.com
Docker Hub: https://hub.docker.com
Example Projects: https://github.com/docker/awesome-compose
This guide should help you get started with Docker and understand its basic concepts. Remember that Docker is a powerful tool with many more features to explore as you become more comfortable with these basics.