Docker Compose build vs image on a VPS
The image key selects an image. The build key builds one. What each means on a VPS, why compose up ignores your Dockerfile change, and the fix.
Docker Compose build vs image: the short answer
In a Docker Compose file, image: identifies the image to use, including a local image, a tag or a digest reference, and build: tells Compose how to build one from source. Set only image: and Compose uses or pulls the image according to pull_policy. Set only build: and Compose builds the image with the configured builder, giving it a name derived from the project name and the service name. Set both and pull_policy controls whether Compose pulls or builds; when it builds, it tags the result with the name in image:, which is how you build an image and push it under a name you chose. The builder can run locally or on a remote Docker host.
That is the whole distinction. Everything below is what it means in operation on a server. This assumes Docker Engine and the Compose plugin are already installed; running Docker on a VPS covers that part.
The three forms in full
Use a published tag, pulling it if it is missing under the default pull policy. No Dockerfile is involved at any point.
services:
web:
image: nginx:1.27
restart: unless-stopped
ports:
- "80:80"Build from a Dockerfile in the project directory. The build can also pull images and download dependencies required by the Dockerfile.
services:
web:
build: .
restart: unless-stopped
ports:
- "80:80"Build and tag the result with docker compose build; without an explicit pull policy, up tries pulling this image before building it. docker compose push can then send that exact tag to a registry.
services:
web:
build:
context: .
dockerfile: Dockerfile
image: registry.example.com/acme/web:1.4.2
restart: unless-stopped
ports:
- "80:80"context is the directory sent to the builder. dockerfile is resolved relative to that context, so context: . with dockerfile: docker/prod.Dockerfile is normal and correct. Run docker compose images to see the image name and image ID behind each service container; check the Compose file to confirm whether the service uses image:, build: or both.
Why does docker compose up not rebuild after I change the Dockerfile?
Because ordinary up reuses an existing image unless you request a build or configure a policy that requires one.
When Compose starts a service that has only a build: section, it uses the existing image if one is available. It does not read your Dockerfile, compare your source files, or look at any timestamp. With both image: and build: and no explicit pull_policy, Compose tries pulling first and builds if the image is unavailable in the registry or platform cache. Present is treated as good enough.
So you edit app.py, run docker compose up -d, watch Compose report the container as running, and serve the old code. Nothing failed, so nothing warned you. The giveaway is the status word Compose prints next to the container name: a container Compose replaced reports as recreated or started, and a container Compose decided to leave alone reports as running.
Two checks settle it. docker compose images prints the image ID each container is using, so note it before the deploy and compare after. docker image ls has a CREATED column, but cached builds and reproducible timestamps mean that date alone does not prove whether your latest source was built.
Which flags force a rebuild
docker compose up -d --buildbuilds first, then recreates any container whose image changed. This is the flag most people are looking for.docker compose build webbuilds one service and starts nothing. Follow it withdocker compose up --no-deps -d webto replace only that container and leave the rest of the stack running.docker compose build --no-cache webbypasses cached layers and rebuilds the service.docker compose build --pullattempts to pull a newer version of the base image inFROM, so a moving tag such asnode:22picks up its current contents instead of the copy you downloaded in March.docker compose up -d --force-recreateforces container recreation even if the configuration and image have not changed. The flag itself does not request a build, butupcan still build when an image is missing or the pull policy requires it. Reaching for this when you meant--buildis a common dead end.
You can also move the decision into the file. In the words of the Compose specification, pull_policy: build means Compose builds the image, and rebuilds it if it is already present. Every up then pays for a build, which is what you want on a laptop and rarely what you want on a server.
services:
web:
build: .
image: registry.example.com/acme/web:dev
pull_policy: buildOne more interaction is worth knowing. docker compose pull tries to pull images for services that have a build section as well, and if that pull fails it tells you the image must be built instead. Pass --ignore-buildable to skip those services quietly.
How the build cache decides your deploy time
The builder checks each Dockerfile instruction for a reusable cached result when that instruction and its inputs are unchanged. For COPY, the inputs include file contents and metadata, excluding modification times. Once one layer misses the cache, subsequent steps that depend on it are rebuilt.
That one rule decides whether your deploy takes seconds or minutes. Order the Dockerfile from what changes rarely down to what changes on every commit.
FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]npm ci sits above COPY . ., so editing a source file leaves the install layer cached and the build resumes at the copy step. Swap those two lines and a one-character change reinstalls every dependency, because COPY . . invalidates the layer that npm ci is built on. The same shape applies to pip install -r requirements.txt and to go mod download.
--no-cache is the right tool when you suspect a stale layer is hiding your fix. It is a bad default, because it throws away the reuse that the Dockerfile ordering exists to earn.
One thing the image sets and Compose can override: the Dockerfile's CMD is what the image runs by default, and a command: key in the service replaces it. How command and entrypoint interact matters here, because a Compose override can make a freshly built image behave exactly like the old one.
Build context and .dockerignore
context: . makes the project directory available to the builder. Without exclusions, that includes .git and any data directory you happen to keep beside your source, although BuildKit skips unused files and transfers changes incrementally. A build that pauses on the transferring-context step of an otherwise unchanged project is telling you the context is too large.
A .dockerignore file at the root of the context excludes paths from that transfer. The syntax is close to .gitignore.
.git
node_modules
*.log
data/
.envThere are two payoffs. The transfer shrinks, reducing time spent sending those files. And COPY . . can no longer copy .env into the image, where anyone who pulls that image can read it back out.
The slow-build case that grows over time is a bind mount. A named volume lives outside your project directory, but a bind mount such as ./data:/var/lib/postgresql/data sits inside the build context, so your builds get slower every week as the database grows. One line in .dockerignore fixes it. Bind mounts against named volumes covers the wider trade.
Build arguments carry a smaller version of the same risk. Values passed through args: can persist in image history or provenance metadata, so put a version number there and never a token. Predefined proxy arguments are excluded from the build cache and docker history by default unless explicitly referenced in the Dockerfile. Env files and secrets in Compose covers where credentials belong instead.
Should you build on the VPS or build elsewhere and pull?
Building on the box that serves your traffic is the default because it is the shortest path: git pull, then docker compose up -d --build. That is fine on a small server nobody depends on yet. It stops being fine for two reasons you can measure and one that only shows up on a bad day.
Memory. A build runs compilers and bundlers next to your live application, and those are the memory-hungry part of most stacks. A JavaScript bundler or a Rust compile can exhaust the memory available on a 1 GB VPS. Under memory exhaustion, the kernel selects an OOM victim using a badness score based on memory use, the allocation context and oom_score_adj; it does not simply kill the largest process. The build can stop with Killed and exit status 137, or your database can be killed instead and the site can go down in the middle of a deploy. dmesg -T | grep -i oom searches the kernel log for OOM messages; access requires permission to read that log.
Disk. Builds leave image layers and build cache behind. docker system df shows their disk use; BuildKit's periodic garbage collection reclaims cache according to its configured policies. Reclaim with docker image prune for dangling images and docker builder prune for cached layers. A full disk stops more than the build. The database stops writing too, and that failure costs far more than a slow deploy.
Reproducibility. Without pushing or exporting it, an image built on the server exists only on that server. If the old image is no longer available, rolling back means checking out the old commit and building again, and that build is not guaranteed to produce what you had, because the base tag moved and the package mirrors moved with it. Building elsewhere and pushing a tag turns a rollback into an edit: point image: at the previous tag and run docker compose up -d.
The arrangement that holds up is plain. Your continuous integration runs the build and pushes registry.example.com/acme/web:<git-sha>, and the Compose file on the VPS carries image: with no build: key at all. Deployment is then two commands that need almost no memory.
docker compose pull
docker compose up -dRun docker login registry.example.com on the server to save credentials for pulling private tags.
Keep the build section for development rather than deleting it, in a file you name yourself.
# compose.dev.yaml
services:
web:
build:
context: .
pull_policy: builddocker compose -f compose.yaml -f compose.dev.yaml up -d --buildName that file compose.dev.yaml and not compose.override.yaml. Compose loads an override file automatically whenever it is present, so a stray override copied to the server would quietly start building there again. Layering several Compose files explains how the merge resolves each key.
The architecture trap when you build elsewhere
A single platform image carries the CPU architecture it was built for. Build an ARM image on an Apple Silicon laptop, push, then use that image on an x86_64 VPS: Docker warns during container creation if it uses an incompatible cached image without an explicit platform. Without emulation, the process fails with exec format error, which reads like a corrupt binary and is not one. Build for the target explicitly:
docker buildx build --platform linux/amd64 \
-t registry.example.com/acme/web:1.4.2 --push .The same mismatch happens in reverse if your laptop is x86 and you run an ARM VPS rather than an x86 one. Letting CI build on the architecture you deploy to removes the question. A multi-platform image also solves this: Docker selects the matching variant when pulling it.
What to check after a deploy
docker compose imagesprints the image and tag behind every running container. A changed image ID is your proof that the new build is in service.docker compose configprints the merged file after variable substitution, so you can read the final image name Compose will use before you run anything.docker compose logs -f webfor the first half minute after the swap. A container that starts and exits repeatedly restarts only if its restart policy calls for it; check the logs for the cause.docker image lsshows a CREATED column. Check the build output and deployed image ID too, because the creation timestamp alone does not prove whether a rebuild ran.
If you are still assembling the file these checks run against, the basics of a Compose file on a VPS covers the surrounding keys, and the Compose command cheat sheet lists the rest of the subcommands.
FAQ
Can I use build and image in the same service?
Yes, and it is the normal setup for a project you build yourself. When Compose builds from the build: section, it tags the result with the value of image:; without an explicit pull_policy, up tries pulling first. That tag is what docker compose push sends to a registry and what another machine pulls. Without an image: key Compose still builds, but it names the image after the project and the service, and it warns that the missing attribute prevents the image being pushed.
Why does docker compose up not pick up my Dockerfile change?
Because ordinary up reuses an existing image unless you request a build or configure a policy that requires one. It does not compare that image against your Dockerfile or source files to decide whether a rebuild is needed. Run docker compose up -d --build, or run docker compose build web followed by docker compose up --no-deps -d web to replace a single service. Setting pull_policy: build on the service makes every up rebuild, which suits a development machine.
What is the difference between --build and --force-recreate?
--build builds the image again, then recreates the containers whose image changed. --force-recreate forces container recreation even if the configuration and image have not changed; it does not itself request a build. If your change is in the source or in the Dockerfile, --build is the flag you want. --force-recreate is for resetting the container itself, for example to clear its writable layer while keeping the same image.
Should I build my Docker images on the VPS or somewhere else?
Build elsewhere and pull a tag once the box also serves traffic. A build competes with your application for memory, and under memory exhaustion the kernel selects a victim using an adjustable OOM score, which can target the build or your database. Builds also leave cache on the disk, although BuildKit reclaims it automatically according to its garbage collection policies. Building on the server stays fine for a small project with no users, and moving later costs little if you keep the build: section in a development-only Compose file.
How do I stop the Docker build cache from filling my disk?
Run docker system df to see how much space your images and your build cache each hold. docker builder prune removes cached layers and docker image prune removes the dangling images left by earlier builds. Adding -a removes all unused build cache or all images unreferenced by containers, respectively; it does not guarantee a completely cold next build. Do not schedule docker system prune -af --volumes on a server, because it removes stopped containers and unused anonymous volumes, putting database data in an anonymous volume at risk during maintenance.