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)
| Feature | Container | Virtual Machine (VM) |
|---|---|---|
| Startup Time | Seconds | Minutes |
| Size | Lightweight (MBs) | Heavy (GBs) |
| OS Isolation | Shares host OS kernel | Has full guest OS |
| Performance | Near-native | Slight overhead |
| Use Case | Microservices, cloud-native | Full 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
| Component | Description |
|---|---|
| Docker Engine | Core runtime to build and run containers |
| Docker Images | Read-only templates used to create containers |
| Docker Containers | Running instances of Docker images |
| Dockerfile | A script to define how to build an image |
| Docker Hub | A 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 loginProvide 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:latestStep 2: Push the Image
docker push your_dockerhub_username/my-first-docker-app:latestYou 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 dataTasks 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
| Instruction | Purpose |
|---|---|
FROM | Base image to build from |
WORKDIR | Set working directory |
COPY | Copy files from host to container |
RUN | Execute commands during image build |
CMD | Default command to run on start |
EXPOSE | Document 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
| Feature | CMD | ENTRYPOINT |
|---|---|---|
| Overridable? | β Yes | π« No (executes always) |
| Use case | Default arguments | Fixed main process |
| Shell/Exec support | Both | Both |
| Best used for | Flexibility | Wrapper 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
| Feature | COPY | ADD |
|---|---|---|
| Copy local files | β Yes | β Yes |
| Extract tar archives | β No | β Yes |
| Download from URLs | β No | β Yes |
| Simpler & more predictable | β Yes | β No |
π§ Best Practice
π‘οΈ Use
COPYby default. Only useADDif 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
- First stage (builder):
- Uses
golangimage to compile the application - Output is the binary
myapp
- Uses
- Second stage:
- Uses lightweight
alpineimage - Copies only the binary from the builder
- Runs the binary using
CMD
- Uses lightweight
βοΈ 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 imagesDisplays:
- Repository
- Tag
- Image ID
- Created
- Size
πΉ Inspect Image Metadata
docker inspect <image-name or image-id>Example:
docker inspect nginxOutputs 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 nginxOutputs:
- 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/shInside container, try:
ls /
cat /etc/os-releaseSome images might use
/bin/bashinstead 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
| Task | Command / Info |
|---|---|
| List all images | docker images |
| Inspect image metadata | docker inspect <image> |
| View image layers | docker history <image> |
| Save image to tar file | docker save -o myimage.tar myimage |
| Load image from tar file | docker load -i myimage.tar |
| Explore image via shell | docker run -it --rm <image> /bin/sh |
| Image storage location | C:\Users\intel\AppData\Local\Docker |