CodeBlanks Logo Icon CodeBlanks

docker build

Learn to build an image from a Dockerfile with docker build.

docker build

docker build produces an image from a Dockerfile. The last argument is the build context: the folder sent to Docker (usually .). -t names the image:

$ docker build -t api:1.0 .
[+] Building 6.3s (10/10) FINISHED
 => [1/4] FROM docker.io/library/python:3.12-slim
 => [2/4] WORKDIR /app
 => [3/4] COPY . .
 => naming to docker.io/library/api:1.0 done

If the Dockerfile has a different name or location it is given with -f: docker build -f docker/Dockerfile.prod -t api:prod .

After the build

The produced image stays in the local store; it is seen with docker images and can be run directly. If you rebuild with the same tag as you change the code, the old image is left untagged (<none>):

$ docker images api
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
api          1.0       4f1e2d3c4b5a   10 seconds ago   162MB
$ docker run --rm api:1.0

Practice Build and run

Write two commands that build the api:1.0 image from the Dockerfile in the current folder, then run it as a container that is deleted when done.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker build -t api:1.0 .
docker run --rm api:1.0

Expected output

[+] Building 6.3s (10/10) FINISHED
 => naming to docker.io/library/api:1.0 done
 * Running on http://0.0.0.0:8000

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the dot in docker build -t api:1.0 . specify?

  • The image name
  • The tag
  • The Dockerfile content
  • The current folder as the build context Correct answer

Explanation: COPY can only access files inside the context.

2 Use a different Dockerfile.

Question
docker build ____ Dockerfile.prod -t api:prod .
Answer
docker build -f Dockerfile.prod -t api:prod .

Explanation: -f (file) gives the Dockerfile path.

3 Match.

Term Meaning
-t Image name and tag
. Build context
-f Dockerfile path
<none> Old image whose tag was taken

All lessons in Beginner