0
0
DockerHow-ToBeginner · 3 min read

How to Use Build in Docker Compose for Custom Images

Use the build key in your docker-compose.yml file to specify the path to a Dockerfile or build context. Docker Compose will build the image before starting the container, letting you customize your app environment easily.
📐

Syntax

The build option in docker-compose.yml tells Docker Compose how to build a Docker image for a service. It can be a simple path or an object with more details.

  • build: The path to the directory containing the Dockerfile.
  • context: The build context directory (usually where the Dockerfile is).
  • dockerfile: Optional, specify a custom Dockerfile name.
  • args: Optional, pass build arguments to the Dockerfile.
yaml
services:
  app:
    build: ./app

# or with more options
services:
  app:
    build:
      context: ./app
      dockerfile: Dockerfile.dev
      args:
        APP_ENV: development
💻

Example

This example shows a simple docker-compose.yml that builds a custom image from a Dockerfile in the ./webapp folder. It then runs a container from that image.

yaml
version: '3.8'
services:
  web:
    build: ./webapp
    ports:
      - "8080:80"
Output
Building web Step 1/3 : FROM nginx:alpine ---> a24bb4013296 Step 2/3 : COPY . /usr/share/nginx/html ---> Using cache ---> 3b1f4a2e7a6b Step 3/3 : EXPOSE 80 ---> Using cache ---> 5d5f3f7a9c1a Successfully built 5d5f3f7a9c1a Successfully tagged project_web:latest Starting project_web_1 ... done
⚠️

Common Pitfalls

Common mistakes when using build in Docker Compose include:

  • Not specifying the correct context path, causing build errors.
  • Forgetting to include a Dockerfile in the build context directory.
  • Using image and build keys incorrectly together, which can cause confusion.
  • Not rebuilding after Dockerfile changes, so old images run.

Always run docker-compose build or docker-compose up --build to rebuild images after changes.

yaml
services:
  app:
    image: myapp:latest
    build: ./app  # This can confuse Docker Compose

# Correct way:
services:
  app:
    build: ./app
    image: myapp:latest  # Optional, tags the built image
📊

Quick Reference

Tips for using build in Docker Compose:

  • Use build: ./path for simple builds.
  • Use the object form to specify context, dockerfile, and args.
  • Run docker-compose up --build to rebuild images automatically.
  • Use image to tag the built image for reuse.

Key Takeaways

Use the build key in docker-compose.yml to specify how to build your service image.
The build option can be a simple path or an object with context, dockerfile, and args.
Always rebuild images after Dockerfile changes using docker-compose build or up --build.
Avoid mixing image and build keys incorrectly to prevent confusion.
Tag your built images with image for easier reuse and management.