Unit 2: Docker CLI Complete Core & Dockerfile
Part D: Docker CLI Complete Core
1. Image Commands
| Command | Purpose |
|---|---|
docker pull IMAGE[:TAG] | Download image |
docker images / ls | List images |
docker build -t NAME:TAG . | Build image from Dockerfile |
docker rmi IMAGE | Remove image |
2. Container Commands
| Command | Purpose |
|---|---|
docker run [OPTIONS] IMAGE | Create + start container |
docker ps -a | List all containers |
docker rm CONTAINER | Remove stopped container |
docker logs -f CONTAINER | Follow logs |
docker exec -it CONTAINER sh | Open shell inside container |
docker stats | Live resource usage |
3. Cleanup Commands
Review carefully before using prune commands, especially volume prune! Data-loss risk.
docker system df(Inspect disk use)docker system prune(Remove unused objects)docker image prune(Remove unused images)
Part E: Dockerfile From Zero
Dockerfile defines how an image is built layer by layer.
1. Instruction Reference
| Instruction | Meaning | Example |
|---|---|---|
| FROM | Base image | FROM python:3.12-slim |
| WORKDIR | Set working directory | WORKDIR /app |
| COPY | Copy local files | COPY . . |
| RUN | Execute build-time command | RUN pip install -r requirements.txt |
| ENV | Set env variable | ENV PYTHONUNBUFFERED=1 |
| EXPOSE | Document intended port | EXPOSE 8000 |
| CMD | Default command | CMD ["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