Docker Compose — Build Context & Dockerfile

1 minute read

The build: key tells Compose to build an image from a Dockerfile instead of pulling one from a registry.

Short Syntax

services:
  api:
    build: ./api

This looks for ./api/Dockerfile and uses ./api as the build context.

Long Syntax

services:
  api:
    build:
      context: ./api
      dockerfile: Dockerfile.prod
Option Default Description
context . Path to the build context
dockerfile Dockerfile Name of the Dockerfile

Project Layout

project/
├── compose.yml
├── api/
│   ├── Dockerfile
│   ├── package.json
│   └── server.js
├── web/
│   ├── Dockerfile
│   └── index.html
services:
  api:
    build: ./api
    ports:
      - "3000:3000"
  web:
    build: ./web
    ports:
      - "80:80"

Build Context Explained

build context = everything sent to Docker daemon

project/api/          ← context directory
├── Dockerfile        ← instructions
├── package.json      ← included
├── server.js         ← included
├── node_modules/     ← included (unless in .dockerignore!)
└── .dockerignore     ← controls what's excluded

.dockerignore

Always create a .dockerignore in your build context:

node_modules
npm-debug.log
.git
.env
*.md

This keeps the build context small and builds fast.

Build + Image (Tag the Result)

services:
  api:
    build: ./api
    image: myregistry/api:latest

This builds the image AND tags it as myregistry/api:latest, making it easy to push.

Running a Build

# Build all services
docker compose build

# Build a specific service
docker compose build api

# Build and start
docker compose up --build

Summary

Feature Example
Short syntax build: ./api
Long syntax build: { context: ./api, dockerfile: Dockerfile.prod }
.dockerignore Exclude files from context
Tag result Add image: alongside build:
Build command docker compose build
Build + start docker compose up --build

Quick Reference

Item Detail
build: ./path Short syntax (context + Dockerfile)
context: Directory sent to Docker daemon
dockerfile: Custom Dockerfile name
.dockerignore Exclude files from build context
build + image Build and tag the result
docker compose build Build all services