Unit 2: Docker CLI Complete Core & Dockerfile

Part D: Docker CLI Complete Core

1. Image Commands

CommandPurpose
docker pull IMAGE[:TAG]Download image
docker images / lsList images
docker build -t NAME:TAG .Build image from Dockerfile
docker rmi IMAGERemove image

2. Container Commands

CommandPurpose
docker run [OPTIONS] IMAGECreate + start container
docker ps -aList all containers
docker rm CONTAINERRemove stopped container
docker logs -f CONTAINERFollow logs
docker exec -it CONTAINER shOpen shell inside container
docker statsLive resource usage

3. Cleanup Commands

Review carefully before using prune commands, especially volume prune! Data-loss risk.

Part E: Dockerfile From Zero

Dockerfile defines how an image is built layer by layer.

1. Instruction Reference

InstructionMeaningExample
FROMBase imageFROM python:3.12-slim
WORKDIRSet working directoryWORKDIR /app
COPYCopy local filesCOPY . .
RUNExecute build-time commandRUN pip install -r requirements.txt
ENVSet env variableENV PYTHONUNBUFFERED=1
EXPOSEDocument intended portEXPOSE 8000
CMDDefault commandCMD ["python","app.py"]

2. Master Python Dockerfile & Cache Strategy

Hinglish: Stable files (jaise requirements.txt) ko pehle copy karo aur install karo. Source code (jo baar-baar change hota hai) baad me copy karo taaki Docker build cache use kar sake.
# syntax=docker/dockerfile:1
FROM python:3.12-slim

WORKDIR /app

# Copy requirements FIRST to use layer caching
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of the code later
COPY . .

ENV PYTHONUNBUFFERED=1
EXPOSE 8000

CMD ["python", "app.py"]

3. Multi-Stage Builds

Use multiple FROM stages so build tools stay in the build stage and only required runtime artifacts enter the final image. This drastically reduces image size and attack surface.

FROM node:22 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Second stage: only the runtime
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html