0
0
DockerHow-ToBeginner · 4 min read

How to Use Docker Build: Syntax, Example, and Tips

Use the docker build command to create a Docker image from a Dockerfile by specifying the build context directory. The basic syntax is docker build -t image_name:tag path_to_dockerfile_directory, which builds the image and tags it for easy use.
📐

Syntax

The docker build command creates a Docker image from a Dockerfile. Here is the basic syntax:

  • docker build: The command to build an image.
  • -t image_name:tag: Assigns a name and optional tag to the image.
  • path_to_dockerfile_directory: The folder containing the Dockerfile and context files.
bash
docker build -t myimage:latest ./app
💻

Example

This example shows how to build a simple Docker image for a Node.js app. The Dockerfile installs Node.js, copies app files, and runs the app.

dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
CMD ["node", "index.js"]
💻

Example

Run this command in the folder containing the Dockerfile to build the image:

bash
docker build -t mynodeapp:1.0 .
Output
Sending build context to Docker daemon 7.68kB Step 1/5 : FROM node:18-alpine ---> 4a3a9a1a7f3d Step 2/5 : WORKDIR /app ---> Using cache ---> 9c1a2b3c4d5e Step 3/5 : COPY package.json . ---> Using cache ---> 7b8c9d0e1f2a Step 4/5 : RUN npm install ---> Running in abc123def456 added 50 packages in 3s Removing intermediate container abc123def456 ---> 1a2b3c4d5e6f Step 5/5 : COPY . . ---> Using cache ---> 2b3c4d5e6f7a Successfully built 2b3c4d5e6f7a Successfully tagged mynodeapp:1.0
⚠️

Common Pitfalls

  • Not specifying the correct build context folder can cause missing files in the image.
  • Forgetting to tag the image with -t makes it harder to find later.
  • Large build contexts slow down the build; use a .dockerignore file to exclude unnecessary files.
  • Running docker build outside the Dockerfile directory without specifying the path causes errors.
bash
Wrong:
docker build

Right:
docker build -t myimage:latest ./app
📊

Quick Reference

OptionDescription
-t image:tagName and tag the image
-f DockerfileSpecify a Dockerfile name or path
--no-cacheBuild image without using cache
--pullAlways attempt to pull a newer base image
pathDirectory with Dockerfile and context files

Key Takeaways

Always specify the build context directory when running docker build.
Use the -t option to tag your image for easy reference.
Keep your build context small with a .dockerignore file to speed up builds.
Run docker build in the directory containing the Dockerfile or specify the path explicitly.
Use docker build options like --no-cache and --pull to control build behavior.