Custom Images
The Lunchbox in Action
Imagine you’re a chef who doesn’t want to rely only on pre‑packaged meals. Instead, you want to design your own recipe - choosing the ingredients, spices, and cooking method. In Docker, that recipe is the Dockerfile, and the dish it produces is your custom image.
By building custom images, developers gain full control over what goes inside their containers, ensuring consistency, portability, and optimization for their specific applications.
Dockerfile Foundations
1. What is a Dockerfile?
- A Dockerfile is a simple text file containing instructions to build a Docker image.
- Each instruction creates a new layer in the image.
- Docker reads the file top‑to‑bottom and executes commands sequentially.
2. Common Dockerfile Instructions
- FROM – Defines the base image (e.g.,
FROM ubuntu:20.04). - RUN – Executes commands inside the image (e.g., installing packages).
- COPY / ADD – Copies files from the host into the image.
- WORKDIR – Sets the working directory inside the container.
- CMD – Defines the default command to run when the container starts.
- EXPOSE – Declares which ports the container listens on.
3. Image Build Process
- Write a Dockerfile.
- Run
docker buildto create the image. - Tag the image for easy identification.
- Run a container from the image.
4. Benefits of Custom Images
- Consistency: Same environment across dev, test, and production.
- Portability: Share images via registries.
- Optimization: Include only what’s needed, reducing size.
- Automation: Reproducible builds with version control.
Hands‑On Lab
Step 1: Create a Dockerfile
# Use a lightweight base image
FROM alpine:latest
# Add a simple command
RUN echo "Hello from my custom image!"
# Default command when container starts
CMD ["echo", "Container started successfully!"]
Step 2: Build the Image
docker build -t hello-image .
-t hello-imagetags the image with a name..specifies the current directory as the build context.
Step 3: Run the Container
docker run hello-image
- Executes the default command defined in the Dockerfile.
Step 4: Inspect the Image
docker inspect hello-image
- Explore metadata, layers, and configuration.
Practice Exercise
- Create a Dockerfile that:
- Uses
ubuntu:20.04as the base image. - Installs
curl. - Sets the working directory to
/app. - Copies a text file into the container.
- Runs
caton the file when the container starts.
- Uses
- Build and run the image.
- Compare its size with the earlier
alpine‑based image.
Visual Learning Model
Dockerfile → docker build → Docker Image → docker run → Container
The Hackers Notebook
Building custom images with Dockerfiles empowers developers to define exactly how their applications run. Each instruction adds a layer, creating a reproducible, portable, and optimized environment. By mastering Dockerfiles, learners unlock the ability to tailor containers for any use case - from simple scripts to complex microservices.
