Building an Image

Use docker build to turn a Dockerfile into a reusable image, tagging it with a name and version.

Syntaxdocker build -t name:tag .

Once you have a Dockerfile, the docker build command turns it into an image.

The build context

The final argument (often .) is the build context — the folder Docker sends to the daemon. Files in this folder can be copied into the image.

Tagging

The -t flag gives your image a name and optional tag in the form name:tag. If you omit the tag, Docker uses latest.

What happens during a build

Docker runs each Dockerfile instruction in order, creating a layer for each. Completed layers are cached, so rebuilds are fast when little has changed.

Example

Example · bash
# Build an image named myapp with tag 1.0 from the current folder
docker build -t myapp:1.0 .

# Build using a Dockerfile with a custom name
docker build -f Dockerfile.prod -t myapp:prod .

# Run the image you just built
docker run -p 3000:3000 myapp:1.0

When to use it

  • A CI job runs docker build on every pull request to verify the Dockerfile still produces a valid image.
  • A developer uses docker build --no-cache during debugging to force all layers to rebuild from scratch.
  • A release engineer builds and tags an image with both the version number and latest before pushing to the registry.

More examples

Basic docker build command

Builds an image tagged myapp:1.0 using the Dockerfile found in the current directory.

Example · bash
# Build image from Dockerfile in current directory
docker build -t myapp:1.0 .

Build with build arguments

Passes build-time variables into the Dockerfile so the same file can produce different images for different environments.

Example · bash
docker build \
  --build-arg NODE_ENV=production \
  --build-arg APP_VERSION=2.1.0 \
  -t myapp:2.1.0 .

Build for multiple platforms

Uses BuildKit to cross-compile and push a multi-architecture image in one command.

Example · bash
docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -t myorg/myapp:latest \
  --push .

Discussion

  • Be the first to comment on this lesson.