0
0
DockerHow-ToBeginner · 3 min read

How to Build a Docker Image from a Dockerfile

To build a Docker image from a Dockerfile, use the command docker build -t image_name:tag . in the directory containing the Dockerfile. This command reads the Dockerfile, executes its instructions, and creates a new image with the specified name and tag.
📐

Syntax

The basic syntax to build a Docker image from a Dockerfile is:

  • docker build: The command to build images.
  • -t image_name:tag: Assigns a name and optional tag to the image.
  • .: The build context, usually the current directory containing the Dockerfile.
bash
docker build -t image_name:tag .
💻

Example

This example shows how to build a simple Docker image that uses the official Alpine Linux base image and creates a file inside the container.

dockerfile
FROM alpine:latest
RUN echo "Hello from Dockerfile!" > /hello.txt
CMD ["cat", "/hello.txt"]
💻

Building the Example Image

Run this command in the directory with the above Dockerfile to build the image named hello-image with tag v1:

bash
docker build -t hello-image:v1 .
Output
Sending build context to Docker daemon 2.048kB Step 1/3 : FROM alpine:latest ---> a24bb4013296 Step 2/3 : RUN echo "Hello from Dockerfile!" > /hello.txt ---> Running in 1a2b3c4d5e6f Removing intermediate container 1a2b3c4d5e6f ---> 7f3b8c9d0e1f Step 3/3 : CMD ["cat", "/hello.txt"] ---> Running in 2b3c4d5e6f7g Removing intermediate container 2b3c4d5e6f7g ---> 9a8b7c6d5e4f Successfully built 9a8b7c6d5e4f Successfully tagged hello-image:v1
⚠️

Common Pitfalls

  • Wrong build context: Running docker build outside the directory with the Dockerfile or missing files causes errors.
  • Forgetting the dot (.): The dot specifies the current directory as context; omitting it leads to errors.
  • Tagging mistakes: Not using -t means the image gets a random ID, making it hard to find.
  • Cache issues: Docker caches layers; changes in Dockerfile might not rebuild layers unless forced.
bash
Wrong:
docker build

Right:
docker build -t myimage:latest .
📊

Quick Reference

CommandDescription
docker build -t name:tag .Build image with name and tag from current directory
docker build .Build image without tag, image ID assigned
docker build -f path/to/Dockerfile .Build using Dockerfile at custom path
docker build --no-cache -t name:tag .Build image without using cache

Key Takeaways

Use docker build -t image_name:tag . in the Dockerfile directory to build an image.
The dot . specifies the build context and must point to the Dockerfile location.
Always tag your images with -t for easy identification and reuse.
Check your build context and Dockerfile path to avoid common errors.
Use --no-cache option to force rebuild without using cached layers.