Session 01

πŸ“¦ What is a Container?

A container is a lightweight, portable, and isolated runtime environment that bundles:

  • Your application code
  • All necessary dependencies (libraries, binaries, configs)
  • Environment variables
  • A minimal runtime

Containers ensure that your application runs consistently across different environments β€” whether on a developer’s laptop, a test server, or in production.


🧊 Think of a Container as:

A portable box that contains everything your app needs to run β€” no matter where you move it, it will work the same.


πŸ†š Container vs Virtual Machine (VM)

FeatureContainerVirtual Machine (VM)
Startup TimeSecondsMinutes
SizeLightweight (MBs)Heavy (GBs)
OS IsolationShares host OS kernelHas full guest OS
PerformanceNear-nativeSlight overhead
Use CaseMicroservices, cloud-nativeFull OS apps, legacy support

πŸ“Έ Container Architecture (Simplified)

+----------------------------+
|        Host OS             |
|  +----------------------+  |
|  | Container Runtime     |  |
|  |  +------------------+ | |
|  |  |   Container App   | | |
|  |  +------------------+ | |
|  +----------------------+  |
+----------------------------+

βœ… Why Containers?

  • Portability: Run your app anywhere (laptop, server, cloud)
  • Consistency: Eliminate “it works on my machine” issues
  • Isolation: Keep apps independent and secure
  • Efficiency: Use fewer resources than virtual machines
  • Scalability: Easily scale containers in/out based on demand

πŸ“Œ Real-world Example

Suppose you’re developing a Python app with Flask that needs Python 3.10 and specific libraries.

If you run it on a machine without those exact versions, it may fail.

With a container, you bundle Python 3.10, Flask, and your app into one image. That image runs the same way on any Docker-enabled system.


πŸ’‘ Containers are essential to modern DevOps, CI/CD, and cloud-native application development.

🐳 Docker and Dockerfile

πŸ“Œ Introduction

Docker is a platform that allows you to build, ship, and run applications in lightweight, portable containers. This guide walks you through:

  • What Docker is
  • Why it’s useful
  • Docker architecture
  • Writing your first Dockerfile
  • Building and running a container

πŸ” What is Docker?

Docker is an open-source tool that helps developers:

  • Package applications and dependencies into a container
  • Run containers consistently across environments
  • Simplify deployment and scaling

βœ… Key Benefits

  • Environment consistency across dev, test, and prod
  • Lightweight compared to virtual machines
  • Fast startup and shutdown
  • Isolated apps (better security and control)

βš™οΈ Docker Architecture

ComponentDescription
Docker EngineCore runtime to build and run containers
Docker ImagesRead-only templates used to create containers
Docker ContainersRunning instances of Docker images
DockerfileA script to define how to build an image
Docker HubA public registry to host and share images

Check the images

docker images

πŸš€ Run Docker Container

docker run <Image name>

πŸ“‹ Check Running and Stopped Containers

docker ps            # Running containers
docker ps -a         # All containers

πŸ“‚ Container Logs

docker logs <container_id>

πŸ” Docker Hub Login

docker login

Provide your Docker Hub username and password.


☁️ Tag and Push Image to Docker Hub

Step 1: Tag the Image

docker tag my-first-docker-app your_dockerhub_username/my-first-docker-app:latest

Step 2: Push the Image

docker push your_dockerhub_username/my-first-docker-app:latest

You can now access it on https://hub.docker.com.


🧹 Docker Cleanup Commands

docker rm <container_id>          # Remove container
docker rmi <image_id>             # Remove image
docker system prune -f            # Remove unused data

Tasks 01

  • Create a mysql db container
  • check the logs if this is failed
  • fix and rerun
  • try to Access you db
  • Convert running container into an image and push to dockerhub.

Task 02

  • Create a container with volumes
docker run -d --name test01 -v <hostlocation:Containerlocation> nginx 
  • Create a container to expose the app to access from browser.
docker run -d --name test01 -p 80:80 nginx 

🧱 What is a Dockerfile?

A Dockerfile is a text file that contains step-by-step instructions on how to create a Docker image.

Conceptual Flow:

Dockerfile β†’ Docker Image β†’ Docker Container

πŸ”§ Common Instructions

InstructionPurpose
FROMBase image to build from
WORKDIRSet working directory
COPYCopy files from host to container
RUNExecute commands during image build
CMDDefault command to run on start
EXPOSEDocument container’s port

πŸ—οΈ Sample Project – Python App in Docker

πŸ“ Directory Structure

myapp/
β”œβ”€β”€ app.py
└── Dockerfile

πŸ“ app.py

print("Hello from Docker!")

πŸ› οΈ Dockerfile

# Use base image
FROM python:3.10-slim

# Set working directory
WORKDIR /app

# Copy app code
COPY app.py .

# Run the script
CMD ["python", "app.py"]

πŸ§ͺ Build and Run the Docker Container

πŸ”¨ Step 1: Build the Image

docker build -t my-first-docker-app .

πŸš€ Step 2: Run the Container

docker run my-first-docker-app

βœ… Output

Hello from Docker!


🧹 Docker Cleanup Commands

docker ps -a               # List all containers
docker rm <container-id>   # Remove a specific container
docker images              # List all images
docker rmi <image-id>      # Remove a specific image

πŸ†š Docker CMD vs ENTRYPOINT: What’s the Difference?

When defining a Dockerfile, you typically use either CMD or ENTRYPOINT to specify what command should be run when the container starts.

While they may look similar, they serve different purposes and behave differently.


πŸ”Ή CMD

  • Provides default arguments for the container’s execution.
  • Can be overridden by command-line arguments passed with docker run.
  • Only one CMD instruction is allowed in a Dockerfile (if multiple are present, only the last is used).

βœ… Example

FROM ubuntu
CMD ["echo", "Hello from CMD"]
docker build -t cmd-example .
docker run cmd-example           # Output: Hello from CMD
docker run cmd-example echo Hi  # Output: Hi

πŸ”Έ ENTRYPOINT

  • Defines the main command that cannot be overridden by arguments passed in docker run.
  • It always runs, and CLI arguments are passed as parameters to it.

βœ… Example

FROM ubuntu
ENTRYPOINT ["echo", "Hello from ENTRYPOINT"]
docker build -t entrypoint-example .
docker run entrypoint-example             # Output: Hello from ENTRYPOINT
docker run entrypoint-example User123     # Output: Hello from ENTRYPOINT User123

πŸ”„ Using ENTRYPOINT with CMD

You can use ENTRYPOINT to define the main command and CMD to provide default parameters.

FROM ubuntu
ENTRYPOINT ["echo"]
CMD ["Hello from both"]
docker run both-example                # Output: Hello from both
docker run both-example "Custom msg"  # Output: Custom msg

🧠 Summary

FeatureCMDENTRYPOINT
Overridable?βœ… Yes🚫 No (executes always)
Use caseDefault argumentsFixed main process
Shell/Exec supportBothBoth
Best used forFlexibilityWrapper for legacy tools, enforced run behavior

πŸ” Use ENTRYPOINT when your container should always run a specific binary, and CMD to supply optional default arguments.

πŸ“‚ Dockerfile: COPY vs ADD – What’s the Difference?

Both COPY and ADD are Dockerfile instructions used to transfer files from your local system into a Docker image during the build process. However, they are not identical.


🟦 COPY

  • Purpose: Simple file/directory copy from local context into the image.
  • Behavior: Only copies files and directories.
  • No extra features (e.g., does not extract archives or support URLs).

βœ… Syntax

COPY <src> <dest>

βœ… Example

COPY app.py /app/
COPY config/ /app/config/

🟨 ADD

  • Purpose: More powerful than COPY, but also more error-prone.
  • Supports:
    • File copying
    • Automatic tar archive extraction
    • Remote URL downloads

βœ… Syntax

ADD <src> <dest>

βœ… Example (with local files)

ADD app.tar.gz /app/     # Automatically extracts to /app/

⚠️ Example (with URL)

ADD https://example.com/file.txt /app/file.txt

βš–οΈ COPY vs ADD: Feature Comparison

FeatureCOPYADD
Copy local filesβœ… Yesβœ… Yes
Extract tar archives❌ Noβœ… Yes
Download from URLs❌ Noβœ… Yes
Simpler & more predictableβœ… Yes❌ No

🧠 Best Practice

πŸ›‘οΈ Use COPY by default. Only use ADD if you need its special features like auto-extraction or remote downloads.


πŸ’‘ Example: When to Use What

# Prefer COPY for clarity
COPY . /app/

# Use ADD only when required
ADD myapp.tar.gz /app/       # Unpacks the archive
ADD https://example.com/config.yaml /app/config.yaml

πŸ—οΈ Docker Multi-Stage Builds


πŸ” What Are Multi-Stage Builds?

Multi-stage builds allow you to use multiple FROM instructions in a single Dockerfile to:

  • Separate the build environment from the runtime image
  • Minimize final image size
  • Improve security and performance

βœ… Why Use Multi-Stage Builds?

In traditional Docker builds:

  • Build tools, compilers, and source files get bundled into the final image
  • This bloats the image and exposes internal code and tools

Multi-stage builds solve this by building your app in one stage, then copying only what’s needed to a second minimal image.


πŸ› οΈ Sample Dockerfile: Go Application

# Stage 1: Builder
FROM golang:1.21 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp

# Stage 2: Final image
FROM alpine:3.19
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]

πŸ“‹ Step-by-Step Explanation

  1. First stage (builder):
    • Uses golang image to compile the application
    • Output is the binary myapp
  2. Second stage:
    • Uses lightweight alpine image
    • Copies only the binary from the builder
    • Runs the binary using CMD

βš–οΈ Advantages

  • 🧹 Cleaner: Only final artifacts in runtime image
  • πŸ” Secure: No compilers, secrets, or source code left behind
  • πŸ“¦ Lightweight: Smaller and faster image

πŸ”§ Additional Notes

  • You can name stages using AS <name> and refer to them with --from=<name>
  • You can have more than two stages (e.g., test, build, package)
  • Multi-stage builds are supported in Docker 17.05+

Maven Build Example

  • Clone the Maven sample Project
git clone https://github.com/khushiramsingh680/studentapp.git
  • Create a Dockerfile
# Stage 1: Builder
FROM maven:3.3-jdk-8 AS builder
WORKDIR /app
COPY . .
RUN mvn clean install

FROM tomcat
WORKDIR /usr/local/tomcat/webapps
COPY --from=builder /app/target/studentapp-2.5-SNAPSHOT.war  .
  • Now Generate an image
docker build -t <name> .
  • Create a container using this image
docker run -d -p 88:8080 <image name>
  • Access your app from Browser
ip:88/studentapp-2.5-SNAPSHOT/

More on Docker Images

🐳 Docker Image Inspection on Windows (Docker Desktop with Hyper-V)

This guide explains how to inspect Docker images on Windows using Docker Desktop with the Hyper-V backend.


πŸ“ Where Are Docker Images Stored?

Docker uses a LinuxKit VM running in Hyper-V to store images. These images are stored inside a virtual disk, not directly accessible from Windows.

  • Virtual Disk Path:
    C:\Users\intel\AppData\Local\Docker\vm-data

πŸ›‘ You cannot browse or open the image files directly here. Use Docker CLI to interact with them.


βœ… Inspect Docker Images Using CLI

πŸ”Ή List All Docker Images

docker images

Displays:

  • Repository
  • Tag
  • Image ID
  • Created
  • Size

πŸ”Ή Inspect Image Metadata

docker inspect <image-name or image-id>

Example:

docker inspect nginx

Outputs detailed JSON metadata:

  • Entrypoint
  • Cmd
  • Environment variables
  • Volumes
  • Exposed ports
  • Labels
  • Layers
  • OS / Architecture

πŸ”Ή Format JSON Output (in PowerShell)

docker inspect nginx | ConvertFrom-Json | Format-List

πŸ”Ή View Image History (Layers)

docker history <image-name>

Example:

docker history nginx

Outputs:

  • Layer creation time
  • Command used (RUN, COPY, etc.)
  • Size of each layer

🐚 Explore Inside an Image (Using a Container)

Run an interactive container and explore the image filesystem:

docker run -it --rm nginx /bin/sh

Inside container, try:

ls /
cat /etc/os-release

Some images might use /bin/bash instead of /bin/sh.


πŸ“¦ Save & Load Docker Images

πŸ”Ή Save Image to .tar File

docker save -o myimage.tar myimagename:tag

πŸ”Ή Load Image from .tar File

docker load -i myimage.tar

❗ Important Notes

  • Docker Desktop stores all image and container data inside a virtual disk managed by Hyper-V.
  • You cannot browse or edit image files directly in C:\Users\intel\AppData\Local\Docker.
  • Always use Docker CLI to inspect, save, or modify images.

πŸ“‹ Quick Summary

TaskCommand / Info
List all imagesdocker images
Inspect image metadatadocker inspect <image>
View image layersdocker history <image>
Save image to tar filedocker save -o myimage.tar myimage
Load image from tar filedocker load -i myimage.tar
Explore image via shelldocker run -it --rm <image> /bin/sh
Image storage locationC:\Users\intel\AppData\Local\Docker