Home Explore Blog CI



docker

1st chunk of `content/manuals/compose/how-tos/dependent-images.md`
1e942286b4400ddfa028587182794ebfb4ba930afb6a0b030000000100000844
---
description: Build images for services with shared definition
keywords: compose, build
title: Build dependent images
weight: 50
---

{{< summary-bar feature_name="Compose dependent images" >}}

To reduce push/pull time and image weight, a common practice for Compose applications is to have services
share base layers as much as possible. You will typically select the same operating system base image for
all services. But you can also get one step further by sharing image layers when your images share the same
system packages. The challenge to address is then to avoid repeating the exact same Dockerfile instruction 
in all services.

For illustration, this page assumes you want all your services to be built with an `alpine` base
image and install the system package `openssl`.

## Multi-stage Dockerfile

The recommended approach is to group the shared declaration in a single Dockerfile, and use multi-stage features
so that service images are built from this shared declaration.

Dockerfile:

```dockerfile
FROM alpine as base
RUN /bin/sh -c apk add --update --no-cache openssl

FROM base as service_a
# build service a
...

FROM base as service_b
# build service b
...
```

Compose file:

```yaml
services:
  a:
     build:
       target: service_a
  b:
     build:
       target: service_b
```

## Use another service's image as the base image

A popular pattern is to reuse a service image as a base image in another service.
As Compose does not parse the Dockerfile, it can't automatically detect this dependency 
between services to correctly order the build execution.

a.Dockerfile:

```dockerfile
FROM alpine
RUN /bin/sh -c apk add --update --no-cache openssl
```

b.Dockerfile:

```dockerfile
FROM service_a
# build service b
```

Compose file:

```yaml
services:
  a:
     image: service_a 
     build:
       dockerfile: a.Dockerfile
  b:
     image: service_b
     build:
       dockerfile: b.Dockerfile
```

Legacy Docker Compose v1 used to build images sequentially, which made this pattern usable
out of the box. Compose v2 uses BuildKit to optimise builds and build images in parallel 

Title: Building Dependent Images with Docker Compose
Summary
This document explains how to build images for Compose services that share common definitions, aiming to reduce image size and build time. It covers using multi-stage Dockerfiles to share base layers and system packages, as well as using one service's image as a base for another. It also discusses the challenges of managing build order dependencies in Compose v2 compared to the sequential builds of Compose v1.