# image Versus build — Docker Compose

Source: https://www.skillbyai.com/en/docker-compose/s-build

> Pull a published image or build your own.

## Pinned images and build contexts

A service either uses an **image** (pulled from a registry, for example `postgres:17`) or a **build** section that builds from a Dockerfile: `context` (the directory sent to the builder), `dockerfile`, `target` (a stage in a multi-stage Dockerfile), and `args`. Pin image versions (`postgres:17`, not `latest`) for reproducibility. Using `build` and `image` together tags the built image with that name, which is useful for pushing it later.

## Images, builds, ports and environment

Each service says where its image comes from, how it is reached, and how it is configured.

![Three ideas: image or build, ports, environment and anchors.](assets/figures/docker-compose/section-2-map.svg) — Figure 2.1 — Images, ports and environment.

## Build settings in the demo

The web service builds the "runtime" stage of a multi-stage Dockerfile; the API builds from ./api; the database uses a pinned image.

```yaml
services:
  web:
    build:
      context: ./web
      target: runtime          # a named stage in web/Dockerfile
  api:
    build: ./api               # short form: just the context
  db:
    image: postgres:${PG_VERSION:-17}
```

## Use .dockerignore

Exclude node_modules, .git and build output from the build context; builds get faster and secrets stay out of images.

**Quiz:** What does build.target select?

- [ ] The Docker host
- [x] A specific stage of a multi-stage Dockerfile
- [ ] A network
- [ ] A registry

*Answer:* A specific stage of a multi-stage Dockerfile. Build only the stage you need.
