Back to course

Lesson 8: Introduction to Dockerfiles

Docker Zero to Hero: The Complete Containerization Course for Beginners

Lesson 8: Introduction to Dockerfiles

While pulling official images is convenient, to containerize your own applications, you must create a custom Docker Image using a Dockerfile.

What is a Dockerfile?

A Dockerfile is a simple text file that contains a series of instructions (commands) that Docker uses to automatically build a new image. These instructions are executed sequentially, creating a new read-only layer for each step.

Creating Your First Dockerfile

Create a new folder called my-app and inside it, create a file named Dockerfile (no extension).

We will create a simple image based on Ubuntu that installs the curl package.

dockerfile

Dockerfile content

1. Start from a base image

FROM ubuntu:latest

2. Set the maintainer (optional, but good practice)

LABEL maintainer="yourname@example.com"

3. Execute commands to update packages and install curl

RUN apt-get update && apt-get install -y curl

4. Define the default command to run when the container starts

CMD ["curl", "--version"]

Building the Image

To build the image, navigate to the directory containing the Dockerfile in your terminal and use the docker build command.

bash

Syntax: docker build [OPTIONS] PATH | URL

docker build -t my-custom-curl-image:v1.0 .

Breakdown:

  • docker build: The command to initiate the build process.
  • -t my-custom-curl-image:v1.0: The tag (-t) we assign to the resulting image. It's good practice to include a version tag.
  • .: The build context (the path to the directory containing the Dockerfile). The dot means 'current directory'.

Docker will execute the instructions line by line, displaying the layer caching process.

Running the Custom Image

After a successful build, run your new image:

bash docker run --rm my-custom-curl-image:v1.0

Result: The container will start, run the CMD instruction (curl --version), print the version information, and then exit (and be removed due to --rm).