Sub topic 8
Building, tagging, and running your image
This chapter assumes you have Docker installed, can run docker commands in a terminal, and have read the earlier chapters on Dockerfile syntax, the build context, and CMD and ENTRYPOINT. Here you turn a Dockerfile into an image, give the image a name, and run it as a container. You also learn the errors that most often block each step.
The build, tag, run workflow
A Dockerfile is only a recipe. Three commands carry it through to a running process:
docker buildreads the Dockerfile and the build context, then produces an image.docker tag(or the-tflag on build) gives that image a human-readable name.docker runcreates a container from the image and starts its default command.
An image is read-only. Each docker run adds a thin writable layer on top and starts a new container. You can run the same image many times, and each container has its own writable layer.
Building an image
Start with the Node.js Dockerfile from earlier in this tutorial:
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]From the directory that contains this file, run:
docker build -t myapp:1.0 .
docker run --rm -p 3000:3000 myapp:1.0The final . is the build context, not the Dockerfile. Docker sends that directory to the builder. By default it looks for a file named Dockerfile at the root of the context. -t myapp:1.0 names the result. --rm removes the container when it stops, and -p 3000:3000 publishes container port 3000 on host port 3000.
Reading build output
Modern Docker uses BuildKit by default. It prints one numbered step per instruction, and a step it reused from cache is marked CACHED. You can check this by running the same build twice. The second run should finish almost at once, with every step marked CACHED.
If you need the full, unabridged output of each RUN step, add --progress=plain:
docker build --progress=plain -t myapp:1.0 .To force a clean rebuild that ignores the cache, add --no-cache. Use it when you suspect a cached step is stale, for example when a RUN command downloads something whose source changed but whose command text did not.
Choosing a Dockerfile or context
Two flags change what the builder reads:
-f path/to/Dockerfileselects a Dockerfile other than the default. The file can live outside the context directory, but anything it copies must be inside the context.- The last argument sets the context. It can be a local directory, a Git URL, or a tarball URL.
docker build -f docker/Dockerfile.prod -t myapp:prod .Passing build arguments
If the Dockerfile declares an ARG, you can set it at build time with --build-arg:
docker build --build-arg NODE_VERSION=20 -t myapp:1.0 .An ARG exists only during the build. A value you set with --build-arg is visible in the image history, so do not pass secrets this way. BuildKit secret mounts, covered in a later chapter, are the safe alternative.
Tagging images
A full image reference has this shape:
registry.example.com/team/myapp:1.0It has four parts: the registry host, a repository path, the image name, and the tag. Each part is optional except the name. If you leave out the registry, Docker assumes Docker Hub. If you leave out the tag, Docker assumes latest.
What a tag really is
A tag is a movable label that points to an image ID. It is not a version stamp. Two points follow from that:
- One image can carry many tags. Moving a tag to a new image takes it away from the old one.
latesthas no special meaning. It is just the default tag name, and nothing makes it the newest build.
Add more tags to an existing image with docker tag:
docker tag myapp:1.0 myapp:1
docker tag myapp:1.0 registry.example.com/team/myapp:1.0
docker images myappNo data is copied. All three names point to the same image ID.
A tagging scheme
A common scheme gives each build a precise tag and a few moving tags:
| Tag | Example | Use |
|---|---|---|
| Full version | `myapp:1.4.2` | Pin an exact release. Never re-point it. |
| Minor or major | `myapp:1.4`, `myapp:1` | Let consumers follow patch or minor updates. |
| Commit hash | `myapp:3f9c2ab` | Trace an image back to its source. |
| `latest` | `myapp:latest` | Convenience for local work only. |
In deployment manifests, use an exact tag or a digest. A digest looks like myapp@sha256:... and identifies the image content itself, so it cannot move.
Running containers
docker run takes the image reference, then optionally a command that replaces CMD.
docker run --rm -p 3000:3000 myapp:1.0Frequently used flags:
| Flag | Effect |
|---|---|
| `--rm` | Delete the container when it exits. |
| `-p HOST:CONTAINER` | Publish a container port on the host. |
| `-d` | Run in the background (detached). |
| `--name web` | Give the container a fixed name. |
| `-e KEY=value` | Set an environment variable at run time. |
| `-it` | Attach an interactive terminal. |
Port publishing
A container has its own network namespace. A process listening on port 3000 inside it is not reachable from the host until you publish the port with -p. The EXPOSE instruction does not do this. It only documents the intended port. The left number of -p is the host port, so -p 8080:3000 makes the same app reachable at localhost:8080.
Many servers listen only on 127.0.0.1 by default. Inside a container that address is the container's own loopback, so published ports cannot reach it. Make the app bind to 0.0.0.0. This is a common reason for a connection that resets or hangs even though the container is running.
Overriding the default command
Arguments after the image name replace CMD. With an ENTRYPOINT, they are appended to it instead. Using the Python example from the earlier chapter:
FROM python:3.12-slim
ENTRYPOINT ["python", "-m", "http.server"]
CMD ["8000"]docker build -t files:1.0 .
docker run --rm -p 9000:9000 files:1.0 9000The container runs python -m http.server 9000. To replace the entrypoint itself, for example to open a shell and inspect the image, use --entrypoint:
docker run --rm -it --entrypoint sh files:1.0Inspecting what is running
Run these in a second terminal while the container is up:
docker ps
docker logs -f web
docker exec -it web sh
docker stop webdocker ps lists running containers, and docker ps -a includes stopped ones. docker logs shows what the process wrote to standard output and standard error. This is why containerized apps should log to those streams, not to files. docker exec starts an extra process inside a running container. docker stop sends SIGTERM, waits ten seconds by default, then sends SIGKILL.
That last point ties back to exec form. With shell form, CMD node server.js runs under /bin/sh -c, and the shell may not forward SIGTERM to your app. The container then takes the full ten seconds to stop and is killed. Exec form makes your process the main process (PID 1), so it receives the signal directly.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `COPY failed: file not found in build context` | The path is outside the context, or `.dockerignore` excludes it. | Check the path relative to the context and review `.dockerignore`. |
| `failed to read dockerfile: open Dockerfile: no such file` | You ran build from the wrong directory, or the file has another name. | Change directory or use `-f`. |
| `port is already allocated` | Another process or container uses the host port. | Pick a different host port, such as `-p 3001:3000`. |
| Container exits immediately | The main process finished or crashed. | Run `docker logs`, then `docker ps -a` to see the exit code. |
| `exec format error` | The image was built for a different CPU architecture. | Build for the target with `--platform linux/amd64`, for example. |
| Name conflict on `--name` | A stopped container still holds the name. | `docker rm web`, or use `--rm`. |
Removing what you no longer need
Images and stopped containers accumulate on disk. Remove them by name or ID:
docker rm web
docker rmi myapp:1.0
docker image prunedocker rmi on a name that shares an image ID with other tags only removes that tag. The image data is deleted once no tag or container uses it. docker image prune removes dangling images, which are untagged layers left behind when a rebuild takes over a tag.
Exercise
You build with docker build -t myapp:2.0 ., then run docker tag myapp:2.0 myapp:latest. A teammate says you now have two images using twice the disk space. Are they right? What does docker rmi myapp:2.0 do afterward?
Show answer
They are not right. docker tag adds a second name to the same image ID and copies no data. After docker rmi myapp:2.0, only that tag is removed. The image stays because myapp:latest still points to it.
Exercise
A container built from your Node.js image is running, and docker ps shows 0.0.0.0:3000->3000/tcp, but curl localhost:3000 from the host resets the connection. The app logs listening on 127.0.0.1:3000. What is wrong and how do you fix it?
Show answer
The app binds only to the container's loopback address, so traffic arriving through the published port cannot reach it. Change the app to listen on 0.0.0.0 (for example, server.listen(3000, '0.0.0.0')), rebuild, and run again.
Exercise
The image from the Python example is built as files:1.0. What command does each of these run? (a) docker run files:1.0 (b) docker run files:1.0 9000 (c) docker run --entrypoint sh files:1.0
Show answer
(a) python -m http.server 8000, because CMD supplies the default argument. (b) python -m http.server 9000, because the argument replaces CMD and is appended to ENTRYPOINT. (c) sh, because --entrypoint replaces the entrypoint, and the image's CMD is cleared, so no extra arguments are passed.