SECTION 03 · 30 MIN READ & EXPLORE
Building Container Images
Package a Flask app with a Dockerfile, understand build layer caching, and inject runtime configuration with environment variables.
How Does a Dockerfile Become an Image?
A Dockerfile is a declarative build recipe where each instruction (FROM, WORKDIR, COPY, RUN, CMD) creates an immutable, cached read-only layer. Ordering stable steps (COPY requirements.txt and RUN pip install) before frequently edited application code (COPY app.py .) keeps rebuilds fast. Environment-specific values should be passed at runtime with -e rather than baked into the image.
From Dockerfile to cached layers and runtime configuration
Experiment freely. Changes disappear when you reset or refresh.
Why and When to Build Custom Images?
Build a custom image whenever you need to package your own application code alongside its exact language runtime and dependencies so it runs identically on any workstation or server.
Explore the files
Dockerfile
FROM python:3.11-slim
# equivalent cd
WORKDIR /app
# Copy files from host to container image
# ADD
COPY requirements.txt .
# Execute command inside image
RUN pip install --no-cache-dir -r requirements.txt
# Copy files from host to container image
COPY app.py .
# Metadata, port to expose when container is run (Docker run -P)
EXPOSE 5000
# Command to run by default (docker run)
# ENTRYPOINT ["nginx"]
CMD ["python", "app.py"]app.py
import os
from flask import Flask
from datetime import datetime
app = Flask(__name__)
# Target Date: CAN 2025 Kickoff - December 21, 2025
TARGET_DATE = datetime(2025, 12, 21, 20, 0, 0)
@app.route("/")
def home():
# 1. Calculate Countdown
now = datetime.now()
remaining = TARGET_DATE - now
if remaining.total_seconds() < 0:
timer_text = "KICKOFF HAS STARTED!"
else:
days = remaining.days
hours, remainder = divmod(remaining.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
timer_text = f"{days} Days, {hours} Hours, {minutes} Minutes, {seconds} Seconds"
# 2. Get Environment Variables (Optional)
player_name = os.environ.get("PLAYER_NAME")
player_num = os.environ.get("PLAYER_NUMBER")
player_html = ""
if player_name and player_num:
player_html = f"<h2>🦁 Featured Player: #{player_num} {player_name}</h2>"
# 3. Simple HTML Template
html_content = f"""
<html>
<head>
<title>CAN 2025 Countdown</title>
<style>
body {{ font-family: 'Verdana', sans-serif; text-align: center; padding-top: 50px; background-color: #c1272d; color: white; }}
h1 {{ font-size: 4em; margin-bottom: 0; }}
.timer {{ font-size: 2em; background: #006233; padding: 20px; border-radius: 10px; display: inline-block; margin-top: 20px; }}
.player {{ margin-top: 30px; font-style: italic; color: #ffbf00; }}
</style>
</head>
<body>
<h1>DIMA MAGHRIB! 🇲🇦</h1>
<h3>Countdown to CAN 2025 Kickoff</h3>
<div class="timer">{timer_text}</div>
<div class="player">{player_html}</div>
</body>
</html>
"""
return html_content
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)requirements.txt
flask==3.0.0Build, run, and configure the countdown app
Build & Run the Image
docker build -t-p# 1. Build the image (the trailing dot sets the build context directory)
docker build -t can-counter:v1 .
# 2. Run the image and publish port 5000 on localhost
docker run --rm -p 127.0.0.1:5000:5000 can-counter:v1Open http://localhost:5000 in your browser, then press Ctrl+C to stop the foreground container.
WHAT TO OBSERVE
Docker executes each Dockerfile instruction as a numbered layer, tags can-counter:v1, and serves the countdown page on http://localhost:5000.
Configure at Runtime Without Rebuilding
-e--name-d# 1. Start the first instance on port 5000
docker run -d --name counter-hakimi -p 127.0.0.1:5000:5000 \
-e PLAYER_NAME="Achraf Hakimi" \
-e PLAYER_NUMBER="2" \
can-counter:v1
# 2. Start a second instance from the exact same image on port 5001
docker run -d --name counter-bono -p 127.0.0.1:5001:5000 \
-e PLAYER_NAME="Yassine Bono" \
-e PLAYER_NUMBER="1" \
can-counter:v1
# 3. Clean up both containers when finished
docker rm -f counter-hakimi counter-bonoWHAT TO OBSERVE
http://localhost:5000 displays #2 Achraf Hakimi while http://localhost:5001 displays #1 Yassine Bono—both running from the exact same immutable can-counter:v1 image.
Observe Layer Caching on Rebuild
COPYRUNdocker image history# 1. After editing app.py, rebuild with a new tag
docker build -t can-counter:v2 .
# 2. Inspect the stacked layers that make up the image
docker image history can-counter:v2WHAT TO OBSERVE
The COPY requirements.txt . and RUN pip install ... steps show CACHED, and only COPY app.py . executes again—finishing in a fraction of a second.
Quick Reference
Dockerfile instructions & image build CLI
Core instructions inside a Dockerfile and the CLI commands used to build and configure images.
Core Dockerfile Instructions
FROM image:tag- Select the base image to build on top of
WORKDIR /path- Set the working directory for subsequent steps
COPY src dest- Copy files from build context into the image
RUN command- Execute a command at build time (new layer)
EXPOSE port- Document the port the process listens on
CMD ["exe","arg"]- Default command executed when container starts
Build & Runtime CLI
docker build -t name:tag .- Build and tag an image from the current folder
docker image history- Inspect the layers and sizes inside an image
docker tag src dst- Add an additional tag to an existing image
docker run -e K=V- Inject an environment variable at runtime
docker build --no-cache .- Force rebuilding every layer from scratch
docker rmi name:tag- Delete a local image tag
Take a moment to explain the idea in your own words.