Skip to content

This repository provides a collection of Dockerfile templates and best-practice examples for building, optimizing, and managing container images. It covers: Core Dockerfile instructions (FROM, RUN, COPY, ENV, etc.). Multi-stage builds & image size optimization. Container orchestration considerations (volumes, networks, Docker Compose)

Notifications You must be signed in to change notification settings

gsurendhar/Dockerfiles

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


Docker: Comprehensive Guide to Images, Containers, and Best Practices


1. Introduction

Docker is a platform that automates the deployment of applications inside lightweight, portable containers.
Containers package your application’s code, dependencies, and runtime into a single image that can run consistently across any environment.

Containers share the host OS kernel, making them far more efficient than traditional virtual machines (VMs). This guide walks through core concepts, commands, Dockerfile instructions, data management, networking, Compose, optimization, best practices, and limitations.


2. Core Concepts

2.1 Images vs. Containers vs. AMIs vs. VMs

  • Image
    A read-only template containing your application and its dependencies. Think of it as a snapshot you can replicate.

  • Container
    A running (writable) instance of an image. You can start, stop, modify, and delete containers without altering the original image.

  • VM (Virtual Machine)
    Includes a full guest OS, system libraries, and applications. Heavier than containers and boots slower.

  • AMI (Amazon Machine Image)
    An AWS-specific VM image (OS + configuration + app). When launched, it becomes an EC2 instance (a VM), not a Docker container.

Component Size Startup Time Isolation Level
Docker Container Tens of MBs Seconds Process & namespace
VM Instance GBs Minutes Full OS virtualization

2.2 Docker Architecture

+-----------+          +--------------+          +-----------------+
| Docker    | <------> | Docker Daemon| <----->  | Docker Registry |
| CLI       |          | (dockerd)    |          | (Docker Hub,    |
|           |          |              |          |  private repo)  |
+-----------+          +--------------+          +-----------------+
          |                                        ^
          v                                        |
      Containers <--- Images <--- Layers <---------+
  • Docker CLI: User interface (docker run, docker build, etc.)
  • Docker Daemon: Manages images, containers, networks, and volumes
  • Registry: Stores and distributes images

3. Essential Docker Commands

3.1 Working with Images and Containers

  • docker pull <image>:<tag>
    Download an image from a registry if not present locally.

  • docker images
    List all images stored locally.

  • docker create <image>
    Create a stopped container from an image without starting it.

  • docker run <image>[:tag]
    Pull (if needed), create, and start a container in one step.

  • docker ps
    List running containers.

  • docker ps -a
    List all containers (running, stopped, exited).

  • docker start <container> / docker stop <container>
    Start or stop an existing container.

  • docker rm <container>
    Remove one or more stopped containers.

  • docker exec -it <container> <command>
    Run a command (e.g., bash) inside a running container.

  • docker inspect <container|image>
    Display low-level details in JSON format.

  • docker rm $(docker ps -aq)
    Bulk-remove all containers.


4. Building Custom Images with Dockerfile

A Dockerfile defines a series of instructions to assemble an image.

# 1. Base image
FROM almalinux:9

# 2. Build-time args
ARG APP_VERSION=1.0

# 3. Environment variables
ENV PORT=80

# 4. Install packages
RUN dnf install -y nginx && \
    dnf clean all

# 5. Copy application code
COPY ./html /usr/share/nginx/html

# 6. Expose port
EXPOSE 80

# 7. Default command
ENTRYPOINT ["nginx", "-g", "daemon off;"]
CMD ["-c", "/etc/nginx/nginx.conf"]

4.1 Key Instructions

  • FROM
    Specifies the base image. Must be the first non-comment instruction.

  • RUN
    Executes commands during image build (e.g., dnf install, pip install).

  • COPY vs. ADD
    Both copy files/directories from build context.
    ADD also supports remote URLs and automatic unpacking of archives.

  • CMD
    Default arguments for ENTRYPOINT or the command to run if no ENTRYPOINT is set. Only one CMD allowed per Dockerfile.

  • ENTRYPOINT
    Configures a container to run as an executable. CMD arguments get appended to ENTRYPOINT.

  • ARG
    Build-time variable. Accessible only during docker build.

  • ENV
    Runtime environment variable, persisted in the image.

  • ONBUILD
    Triggers instructions when the image is used as a base by another Dockerfile.

4.2 Building and Tagging

# Build the image, tag it as joindevops/webapp:v1
docker build -t joindevops/webapp:v1 .

5. Managing Data: Volumes and Bind Mounts

Containers are ephemeral by default. To persist data:

5.1 Types of Storage

Type Managed by Docker Use Case
Bind mount No Dev: map host code → container
Named volume Yes Prod: database storage
tmpfs mount Yes Sensitive ephemeral data (in RAM)

5.2 Usage Examples

  • Bind mount
    docker run -v /host/path:/container/path nginx

  • Named volume

    docker volume create db_data
    docker run -v db_data:/var/lib/mysql mysql

6. Networking

6.1 Network Drivers

  • bridge (default)
    Containers get a private subnet; no cross-host communication.

  • host
    Container uses host’s network stack directly (no isolation).

  • none
    Container has no network interfaces.

  • overlay
    Multi-host networking (Docker Swarm or Compose).

6.2 Custom Bridge Network

docker network create roboshop-net
docker run -d --name redis \
  --network roboshop-net \
  redis:7
docker run -d --name mongodb \
  --network roboshop-net \
  joindevops/mongodb:v1

Containers on the same bridge network can discover each other by name.


7. Docker Compose

Defines and manages multi-container applications using a docker-compose.yml file.

version: "3.8"
services:
  catalogue:
    image: joindevops/catalogue:v1
    networks:
      - roboshop-net

  cart:
    image: joindevops/cart:v1
    depends_on:
      - catalogue
    networks:
      - roboshop-net

  mongodb:
    image: mongo:5
    volumes:
      - db_data:/data/db
    networks:
      - roboshop-net

networks:
  roboshop-net:

volumes:
  db_data:
  • docker-compose up -d to start all services.
  • docker-compose down to stop and remove.

8. Multi-Stage Builds & Layer Optimization

Separate build environment from runtime:

# Stage 1: Build
FROM maven:3.8 AS builder
WORKDIR /app
COPY . .
RUN mvn package -DskipTests

# Stage 2: Runtime
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY --from=builder /app/target/app.jar .
CMD ["java", "-jar", "app.jar"]
  • Eliminates unnecessary tools from final image.
  • Reduces image size and attack surface.

Combine multiple RUN commands with && to minimize layers.


9. Best Practices

  • Use minimal official base images (Alpine, Slim variants).
  • Run processes as non-root users (USER appuser).
  • Exclude unneeded files with .dockerignore.
  • Define health checks to monitor container health.
  • Set resource limits: --memory, --cpus.
  • Avoid storing secrets in images; use secret managers or environment variables securely.
  • Tag images with semantic versions; avoid latest in production.

10. Limitations & Orchestration

Docker alone does not provide:

  • Auto-scaling
  • Load balancing
  • Self-healing (auto-restart requires extra flags or restart policies)
  • Cross-host networking out of the box
  • Resilient storage across host failures

For production-grade deployments, integrate with an orchestration platform such as Kubernetes or Docker Swarm to handle scaling, service discovery, rolling updates, and persistent storage.


With these foundations—core concepts, commands, Dockerfile instructions, data management, networking, Compose, multi-stage builds, and best practices—you can build robust, efficient, and maintainable containerized applications.

About

This repository provides a collection of Dockerfile templates and best-practice examples for building, optimizing, and managing container images. It covers: Core Dockerfile instructions (FROM, RUN, COPY, ENV, etc.). Multi-stage builds & image size optimization. Container orchestration considerations (volumes, networks, Docker Compose)

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published