tezvyn:

Compose image directive versus build directive

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Compose service definition.

OUTLINE

image pulls a prebuilt image from a registry; build builds from a local Dockerfile and context; use build for your own custom application code.

WHAT THIS TESTS It checks whether you understand the two ways a Compose service gets its image and when each is appropriate.

A GOOD ANSWER COVERS The image directive points to an existing image reference, such as postgres:16, and Compose pulls it from the registry if it is not present locally. The build directive specifies how to build the image from source: a context directory and optionally a Dockerfile path and build args. You reach for build when the service is your own application whose image is not published anywhere, so it must be compiled from your local Dockerfile. Third-party dependencies like databases or caches use image. The two can be combined: providing both build and image makes Compose build the image and tag it with the given name, which is handy for pushing later. docker compose build and docker compose up --build trigger or refresh the build.

COMMON WRONG ANSWERS Thinking image can build from a Dockerfile. Believing build and image cannot coexist. Forgetting that without --build, Compose may reuse a stale built image. Using build for stock third-party services where a registry image already exists.

LIKELY FOLLOW-UPS How do you force a rebuild? What does specifying both image and build do? How do build args and target work here?

ONE CONCRETE EXAMPLE The db service uses image: postgres:16 (pulled from the registry). The web service uses build: context: ./web because it runs your in-house Flask app with no published image. Running docker compose up --build builds web from ./web/Dockerfile while simply pulling Postgres.

Read the original → docs.docker.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.