docker build
Learn how docker build turns a Dockerfile into an image, what the build context is, how layer caching works, and which flags control the build
docker build is the command that turns a Dockerfile into an image. It reads the Dockerfile, sends the build context to the Docker daemon, runs each instruction in order, caches each step as a layer, and stores the finished image under a name and tag. Every image on the earlier pages in this cluster was produced by this one command, and this page is about how it works, what its flags do, and what to do when it fails.
Docker itself is not installed on the machine used to write these docs, so no docker build command on this page was run live here. Every flag and behaviour follows the official Docker command reference, and the Rust code the builds package was compiled and run directly with cargo to prove the server itself works.
Where This Fits
The Dockerfile, the multi-stage split, and the runtime image are all descriptions of what should be built. docker build is the act of building it. Until this command runs, the Dockerfile is only a text file, and the image it describes does not exist anywhere. After it runs, the image sits in local storage, ready to be run, listed, inspected, or pushed to a registry.
Think of the Dockerfile as a recipe and docker build as the cooking. The recipe can be read, corrected, and argued about, but it feeds nobody until someone follows it in a kitchen. The build command is the cook. It gathers the ingredients from the build context, follows the steps in order, and produces the finished dish, the image, which can then be served again and again without cooking it from scratch each time.
The Smallest Working Version
Start with the same project as the earlier Docker pages, in a folder with the Dockerfile, the .dockerignore file, and the Rust source.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
FROM rust:1.100.0-bookworm AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN cargo fetch
COPY src ./src
RUN cargo build --release
FROM debian:bookworm-slim
WORKDIR /app
COPY /app/target/release/axum-project /usr/local/bin/axum-project
EXPOSE 3000
CMD ["/usr/local/bin/axum-project"]
target/
.git/
.env
Dockerfile
.dockerignore
The smallest build command, run in the project root on a machine with Docker installed, is:
docker build -t axum-project:1.0 .
Three parts make up the command. docker build is the command itself. -t axum-project:1.0 tags the finished image with the name axum-project and the tag 1.0, so it can be referred to by that name later. The final . is the build context, the folder Docker reads files from, which here is the current directory. Docker looks for a file named Dockerfile in that folder, reads it, and builds the image from it.
When the build finishes, the image is stored locally and can be listed:
docker images axum-project
The output lists the image name, its tag, and its size, which confirms the build produced something. The tag 1.0 is a version label the developer chooses. If no tag is given, Docker uses latest, which is a label like any other, not a promise that the image is the newest one. A deliberate version tag is better, because latest moves every time an image is built without a tag, and two machines can hold different images under the same latest label.
Working Setup:
If docker build -t axum-project:1.0 . finishes without an error and docker images axum-project shows the image with the tag 1.0, the build worked. The next proof is docker run, which starts a container from the finished image.
Docker Is Not Installed Here:
Every Docker command on this page is written from the official Docker docs, not from a live run on this machine. The Rust code was compiled and run with cargo, and the image tags were checked against Docker Hub, but no image was built while writing this page. Install Docker from the official Docker install guide before running the commands.
Understanding the Command Piece by Piece
The command has a shape that stays the same no matter how many flags are added, and each part has one job.
docker build [OPTIONS] PATH
PATH is the build context, and it is the only required argument. It is usually ., the current directory, and it can also be a path to another folder, or a URL to a Git repository, which Docker clones and builds. The context is the folder Docker is allowed to read files from. A COPY instruction can only copy files that are inside the context, and a file outside it is invisible to the build, no matter how the Dockerfile spells the path.
The options come before the path, and the most used ones are -t, -f, --target, --build-arg, --no-cache, and --progress. Each one is covered below, because each one changes the build in a way a beginner will meet in real projects.
The -t flag names the image
docker build -t axum-project:1.0 .
docker build -t axum-project:1.0 -t axum-project:latest .
The -t flag, short for --tag, gives the finished image a name and an optional tag, in the form name:tag. Without it, the image is built but has no name, and it can only be referred to by its image ID, a long hash that nobody remembers. An image can carry more than one tag by repeating the flag, so one build can label the image both 1.0 and latest at once. The name can also include a registry address, such as registry.example.com/team/axum-project:1.0, which is the name the image needs before it can be pushed to that registry.
The -f flag picks a different Dockerfile
docker build -f Dockerfile.dev -t axum-project:dev .
The -f flag, short for --file, tells Docker to use a different file as the Dockerfile. The default is a file named Dockerfile in the build context. A project with a development Dockerfile and a production Dockerfile uses -f to choose between them, while the build context stays the same folder. The path given to -f is read from the machine running the command, and the file it names must still be inside the build context rules for its COPY instructions.
The --target flag stops at one stage
docker build --target builder -t axum-project:builder .
The --target flag builds up to a named stage and stops there, producing an image of that stage instead of the final one. It is the debugging tool from the multi-stage build. With BuildKit, the current default builder, only the stages the target depends on are built, so an unrelated stage is skipped. A plain build with no --target flag builds every stage up to the last one, and the last stage becomes the image.
The --build-arg flag sets a build-time variable
docker build --build-arg RUST_VERSION=1.99.0 -t axum-project:1.0 .
The --build-arg flag sets a value for an ARG instruction in the Dockerfile. It only works for variables the Dockerfile declares with ARG, and it only affects the build. The value does not survive into the finished image or the running container. The Dockerfile on the earlier pages declares ARG RUST_VERSION=1.100.0 before its first FROM, so this flag can change the compiler version for one build without editing the file. A build argument must never carry a secret, because its value is visible in the image history.
The --no-cache flag rebuilds everything
docker build --no-cache -t axum-project:1.0 .
The --no-cache flag tells Docker to ignore the layer cache and run every instruction again from scratch. It is the fix for a build that behaves strangely after a change that Docker did not notice, and it is the right flag for a release build that must be provably fresh. It makes the build slower, because the dependency download and the full compile run again, so it is a troubleshooting and release tool, not an everyday flag.
The --progress flag controls the output
docker build --progress=plain -t axum-project:1.0 .
The --progress flag controls how much the build prints. The default output is a compact progress display that updates in place. The plain value prints every step as plain text, one line after another, which is easier to read in logs and in continuous integration, where the compact display cannot update in place. The plain output is also the right choice when a build fails and the error needs to be copied out of the log.
The Build Context and the .dockerignore File
The build context is the folder Docker sends to the daemon before the build starts, and its size decides how long the build takes to start. Docker sends the whole context, except the files listed in .dockerignore, and a context that includes the target directory or the .git history can be hundreds of megabytes, which the daemon must receive before the first instruction runs.
The .dockerignore file uses the same pattern style as .gitignore, with one pattern per line, and it sits beside the Dockerfile:
target/
.git/
.env
Dockerfile
.dockerignore
Each line removes a set of files from the context. target/ is the largest win, because a release build directory holds compiled dependencies and intermediate files. .git/ is the version control history, which the build never needs. .env is the secrets file, which must never reach the daemon or the image. The last two lines exclude the Dockerfile and the ignore file themselves, which the build does not need to copy.
A beginner can check what the context contains by listing the project folder and mentally removing the ignored entries. If the folder holds a large target directory and no .dockerignore file, the build sends all of it, and the first fix for a slow build is the ignore file, not a faster machine.
A Missing .dockerignore Slows Every Build:
Without a .dockerignore file, docker build sends the target directory, the .git history, and the .env file into the build context on every build. The build gets slower, and a secret in .env can reach the image history. Add the ignore file before the first build, not after the first slow one.
How Layer Caching Works
Each instruction in the Dockerfile produces one layer, and Docker caches each layer by its inputs. When a build runs, Docker checks each instruction in order. If the instruction and its inputs are unchanged since the last build, Docker reuses the cached layer and prints that the step was cached. If anything changed, Docker reruns that instruction and every instruction after it, because a later layer builds on the earlier one.
The order of instructions decides how much of the build is cached. The Dockerfile in this cluster is ordered from the most stable to the most changeable: the base image first, then the manifest files, then the dependency fetch, then the source code, then the compile. A change to src/main.rs invalidates only the source copy and the compile, while the dependency download stays cached. A change to Cargo.toml invalidates the fetch and everything after it, because the dependencies themselves changed.
The dummy main trick from the multi-stage build exists because cargo compiles dependencies and the program in one pass. Copying the manifests, building a placeholder program to compile the dependencies, and then copying the real source means a source change recompiles only the program crate. That trick was checked in the scratch project used for these docs by running the same two cargo builds directly, and the second build compiled only the axum-project crate.
A cache is not always trustworthy. A base image can be updated on the registry, a package repository can change, or a RUN line can depend on the network, and Docker has no way to know the result would differ. The --no-cache flag is the answer when a build behaves oddly, and the --pull flag, shown below, forces Docker to check for a newer base image before building.
Reading the Build Output
BuildKit, the current default builder, prints one line per step as the build runs. Each line names the stage and the instruction, and it ends with a status. A cached step is marked as cached, and a step that ran is marked as done. A build that reuses most of its cache finishes quickly, with most steps marked cached, and only the steps after the last change actually running.
The exact text of the output depends on the Docker version and the --progress setting, so this page does not reproduce a full build log as if it were captured live. What matters is the shape: one line per instruction, in Dockerfile order, with the slowest steps, the dependency fetch and the release compile, taking the longest. A step that fails stops the build at once, and the error names the instruction and the reason, which is the starting point for the fixes below.
When a build fails, the output above the error is as useful as the error itself. The last cached step shows how far the build got, and the failing step shows which instruction broke. A COPY failure means a file was missing from the context or from the named stage. A RUN failure means the command itself failed, and the command output above the error usually names the cause, such as a missing package or a compile error.
More Flags Worth Knowing
Three more flags appear often enough to deserve a short explanation each.
docker build --pull -t axum-project:1.0 .
The --pull flag tells Docker to check the registry for a newer version of the base images before building, and to download it if one exists. Without it, Docker reuses the base image already stored locally, even if a newer one has been published. A release build should use --pull, so the image is built on the newest base, and a local development build can skip it, so it stays fast.
docker build --build-arg RUST_VERSION=1.100.0 --label version=1.0 -t axum-project:1.0 .
The --label flag adds metadata to the finished image, as key and value pairs. Labels record facts like the version, the maintainer, or the commit the image was built from, and they can be read later with docker inspect. They do not affect how the image runs.
docker build -q -t axum-project:1.0 .
The -q flag, short for --quiet, suppresses the build output and prints only the image ID when the build finishes. It is useful in scripts, where the output would only clutter the log, and the image ID is the one value the script needs next.
The Concept Behind the Build
A build is a pure function of its inputs. The inputs are the Dockerfile, the build context, the base images, and the build arguments. The output is the image. Given the same inputs, the build should produce the same image, and that property is what makes Docker images trustworthy. A machine that builds the image from the same Dockerfile and the same source gets the same result as the machine that built it first.
That property is why pinning matters. An unpinned base image, such as rust:latest, can change between two builds, so the same Dockerfile produces different images on different days. A pinned tag, such as rust:1.100.0-bookworm, fixes the input, so the output is stable. The same logic applies to the manifests. Cargo.lock pins every dependency version, so the build compiles the same dependency versions every time, and the Dockerfile copies the lock file for exactly that reason.
The cache is a shortcut, not a change to the function. A cached layer is a stored result for inputs that have not changed, and Docker reuses it because rerunning the instruction would produce the same layer. The --no-cache flag removes the shortcut and runs the function from scratch, and the result should be the same image, just built more slowly.
Why This Design
The build command is shaped by two pressures, and each one explains a flag or a habit.
The first pressure is speed. Rust builds are slow, and the dependency compile dominates the build time. Layer caching, the manifest-first order, and the dummy main trick all exist to keep a rebuild after a one-line change short. A build that takes minutes on the first run and seconds on the next is the sign the caching is working.
The second pressure is trust. An image that cannot be rebuilt from its inputs is not a reliable artifact. Pinned tags, a lock file, and a .dockerignore file that keeps secrets out of the context all make the build reproducible and safe to share. A build that depends on a file outside the context, or on a secret passed as a build argument, breaks that trust, and the failure shows up later, on a different machine, at the worst time.
A Richer Complete Example
The richer example builds the config-driven server from the earlier pages, with the four-field AppConfig, and it uses a development Dockerfile alongside the production one, to show how -f picks between them.
FROM rust:1.100.0-bookworm AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN cargo fetch
COPY src ./src
RUN cargo build --release
FROM debian:bookworm-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
COPY /app/target/release/axum-project /usr/local/bin/axum-project
USER nobody
EXPOSE 3000
CMD ["/usr/local/bin/axum-project"]
FROM rust:1.100.0-bookworm
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN cargo fetch
COPY src ./src
EXPOSE 3000
CMD ["cargo", "run"]
The development Dockerfile is a single stage that keeps the compiler and the source, and its CMD runs cargo run instead of the release binary. It is slower to start and larger to store, but a code change inside the container is a cargo run away, which suits a development loop. The production Dockerfile is the two-stage file, which is what ships. The two files share the same project folder and the same build context, and the build command chooses between them:
docker build -f Dockerfile.dev -t axum-project:dev .
docker build -t axum-project:1.0 .
The Rust files are the same as in the Dockerfile example: src/config.rs with the four-field AppConfig, src/lib.rs declaring the module, and src/main.rs binding to the address from the config and serving / and /health. The server code was compiled and run directly with cargo in the scratch project, and a request to / returned the listen address and log level as JSON while /health returned OK. The Dockerfiles themselves need Docker installed to be proven, and the commands above follow the official Docker command reference.
How the Build Flows
The path from a command to a stored image has five steps, and each one produces something the next one uses.
docker build -t axum-project:1.0 .
|
v
build context sent to the daemon, minus .dockerignore entries
|
v
each Dockerfile instruction runs in order, cached layers reused
|
v
final stage becomes the image, earlier stages discarded
|
v
image stored locally as axum-project:1.0
The context step is the one beginners overlook, because it happens before any instruction runs. A large context makes the build slow before the first line of the Dockerfile is even read, and the .dockerignore file is the fix. The final step is the one that matters for running the image, because docker run can only start an image that is already stored locally.
Testing It Without a Docker Daemon
A full test needs Docker, but the inputs to the build can be checked on this machine, and each check catches a different failure before the build is ever attempted.
First, prove the server code compiles and passes its tests. The scratch project ran cargo check, cargo test, and cargo build --release for the code on this page, and started the server with the environment variables set in the shell. A build that packages broken code produces a broken image, so the code must be proven first.
Second, check the build context. List the project folder, confirm that target/, .git/, and .env are excluded by .dockerignore, and confirm that every file a COPY instruction names is inside the context. A COPY source that does not exist in the context fails the build with a file-not-found error, and that failure is avoidable by reading the folder first.
Third, read the Dockerfile against the reference, line by line. The first instruction is FROM, every stage has a name, every COPY --from source is an absolute path inside the named stage, and the binary path matches the path cargo build --release produces. The image tags were checked against Docker Hub while writing these docs, and rust:1.100.0-bookworm and debian:bookworm-slim both exist.
The checks that need Docker are the build itself, the image listing, and the size comparison between the single-stage and multi-stage images. Those are the first commands to run once Docker is installed.
Common Beginner Mistakes
Forgetting the final dot
# Wrong - no build context given
docker build -t axum-project:1.0
The command needs a path for the build context, and the . at the end is that path. Without it, Docker reports that a context is required. The fix is to add the . when the Dockerfile and the source are in the current directory.
Building from the wrong directory
# Wrong - run from the parent folder, the Dockerfile is not here
cd ..
docker build -t axum-project:1.0 .
Docker looks for the Dockerfile in the build context, and a context that does not contain one fails at once. The fix is to run the command from the project root, where the Dockerfile sits, or to pass the right context path and the -f flag for the Dockerfile location.
COPY failing because the file is outside the context
# Wrong - ../shared/config.toml is outside the build context
COPY ../shared/config.toml /app/config.toml
A COPY source must be inside the build context, and a path that climbs out of it with .. is rejected. The fix is to put the file inside the project folder, or to pass a larger folder as the context and adjust the paths, so every source the Dockerfile needs is inside the context.
Passing a secret as a build argument
# Wrong - the value stays in the image history
docker build --build-arg JWT_SECRET=dev-secret -t axum-project:1.0 .
Build arguments are visible in the image history, so a secret passed this way is baked into the image. The fix is to keep secrets out of the build entirely and pass them at runtime with docker run -e or --env-file, which is how runtime variables are passed.
Rebuilding with --no-cache on every run
The --no-cache flag is a troubleshooting tool, not a default. A build that always uses it recompiles every dependency on every run, and a Rust build that takes minutes becomes the cost of every one-line change. The fix is to use the cache by default, and to reach for --no-cache only when the build behaves oddly or a release must be provably fresh.
Tagging everything latest
# Wrong - two different images share one label
docker build -t axum-project:latest .
The latest tag moves with every untagged build, so two machines can hold different images under the same label, and a rollback becomes guesswork. The fix is a deliberate version tag, such as axum-project:1.0, with latest added as a second tag only when it is wanted, never as the only tag.
Secrets in Build Arguments Stay in the Image:
A value passed with --build-arg is recorded in the image history, and anyone with the image can read it. Build arguments are for non-secret values such as a compiler version. Secrets belong at runtime, never in a build flag.
Final Complete Example
Everything on this page put together is the project, the two Dockerfiles, the ignore file, and the build commands that produce the image.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
dotenvy = "=0.15.7"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
FROM rust:1.100.0-bookworm AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN cargo fetch
COPY src ./src
RUN cargo build --release
FROM debian:bookworm-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
COPY /app/target/release/axum-project /usr/local/bin/axum-project
USER nobody
EXPOSE 3000
CMD ["/usr/local/bin/axum-project"]
target/
.git/
.env
Dockerfile
.dockerignore
Check the code first, then build on a machine with Docker:
cargo check
cargo test
docker build -t axum-project:1.0 .
docker images axum-project
The first two commands were run for this page in the scratch project and passed. The last two follow the official Docker command reference and need Docker installed. When the build finishes, docker images shows the image with the tag 1.0, and the image is ready to run.
Summary
docker build is a function from inputs to an image, and the quality of the image follows from the quality of the inputs. A clean context, pinned tags, a lock file, and a Dockerfile ordered from stable to changeable produce a fast, reproducible build. A context full of build artifacts, an unpinned base, and a secret passed as a build argument produce a slow, unrepeatable, unsafe one. The flags do not change that equation. They only control which Dockerfile is read, which stage is built, which version the image carries, and whether the cache is trusted for this run.
The decision framework is short. Build from the project root, tag with a version, keep the context clean, trust the cache by default, and rebuild from scratch only when something behaves oddly or a release must be fresh. With those habits, the build becomes the boring, reliable step it is meant to be, and the interesting work moves to running the image, where it actually serves requests.