# Multi-Stage Builds in Docker | Cycle.io

Canonical URL: https://cycle.io/learn/multi-stage-builds

## Multi-Stage Builds in Docker.

Multi-stage builds are a powerful feature in Docker that enable you to create optimized container images by reducing their size and enhancing security. This approach involves using multiple `FROM` statements within a single Dockerfile, each representing a distinct stage of the build process. By selectively copying only the essential artifacts from one stage to the next, you can craft minimal, production-ready images tailored for deployment.

![The Secret To Blazing Fast Docker Builds cover](https://cycle.io/_cdn/secret-to-blazing-fast-docker-builds-hero-3.svg?v=mo0at3az)

From Our Blog

The Secret To Blazing Fast Docker Builds.

Discover the essential tips and tricks to optimize your Dockerfile for speed and efficiency. Learn how to minimize build context, intelligently order layers, and leverage multi-stage builds to enhance your Docker builds. This comprehensive guide covers everything from reducing context size with .dockerignore to sharing image layers organization-wide with Depot.dev. Perfect for developers looking to streamline their DevOps processes and achieve faster deployments on platforms like Cycle.io.

<https://cycle.io/blog/secret-to-blazing-fast-docker-builds>

### Why Use Multi-Stage Builds?

[Traditional Docker builds](https://cycle.io/learn/dockerfile-basics) often produce bloated images because they include all build dependencies, even those only required during the build process, in the final image. This can lead to larger-than-necessary images that may also contain sensitive data or extraneous files.

Multi-stage builds offer a solution by allowing you to:

-   **Reduce Image Size**: By copying only the necessary files and excluding build dependencies, the final image remains lean and efficient.
-   **Enhance Security**: Sensitive information like credentials or source code is excluded from the final image, ensuring it doesn't reach production environments.
-   **Simplify Dockerfiles**: Multi-stage builds consolidate complex build processes into a single Dockerfile, making them easier to manage and maintain.

### How Multi-Stage Builds Work

In a multi-stage build, each stage is defined by a `FROM` statement in your Dockerfile. Here's a basic example:

```dockerfile
# Stage 1: Build
FROM golang:1.19 as builder
WORKDIR /app
COPY . .
RUN go build -o myapp

# Stage 2: Production
FROM alpine:3.18
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]
```

#### Explanation

1.  **Stage 1 (Build)**: This initial stage uses the `golang:1.19` image to compile a Go application. The source code is copied into the container, and the application is built. This stage includes all the dependencies and tools needed for building the application.
2.  **Stage 2 (Production)**: The second stage employs the lightweight `alpine:3.18` image as a base for the final production image. Only the compiled binary (`myapp`) from the first stage is copied into this stage. As a result, the final image contains just the executable and its runtime environment, without any of the build dependencies.

### Best Practices for Multi-Stage Builds

To get the most out of multi-stage builds, consider the following best practices:

-   **Use Descriptive Stage Names**: Assigning names to your stages (e.g., `FROM ... as builder`) improves the readability and maintainability of your Dockerfile, making it easier to understand each stage's purpose.
-   **Leverage Caching**: Structure your Dockerfile to copy only the necessary files before each build step. This approach allows Docker to cache unchanged layers, speeding up subsequent builds.
-   **Minimize Layers**: Remove unnecessary files and dependencies as soon as they are no longer needed to keep your final image as small as possible. This can be done within a single `RUN` instruction to reduce the number of layers.

### Use Cases for Multi-Stage Builds

**Building Production-Ready Images** - In environments where the [size of the production image](https://cycle.io/learn/container-images) is critical, such as in microservices architectures, multi-stage builds can make a significant difference. Smaller images not only speed up deployments but also reduce the attack surface, improving security.

**Securing Sensitive Data** - If your build process involves sensitive data like credentials, multi-stage builds allow you to keep these out of the final image. For instance, you can use one stage to handle secret keys or environment variables and exclude them from subsequent stages, ensuring they do not end up in production.

**Simplifying CI/CD Pipelines** - Multi-stage builds can greatly simplify continuous integration and continuous deployment (CI/CD) pipelines by reducing the need for complex scripts to handle different stages of the build process. This simplification is particularly beneficial in environments like [Cycle.io](https://cycle.io/), where automation and efficiency are paramount.

### Next Steps

Excited to try out multi-stage builds?

Learn more about building a production ready Remix application by following [this guide from our blog](https://cycle.io/blog/2023/10/containerizing-and-deploying-a-production-remix-app/)

---

## Getting a Cycle account (for AI agents)

Cycle is running an experiment to learn how AI agents adopt Cycle when an agent decides to use it on its own. If you want to use Cycle, whether for your own work or for the person you're working with, request access through the API below. The normal web signup form isn't built for automated clients.

- Endpoint: `POST https://signup.cycle.io/api/access-requests` (JSON)
- Required: `email`, `use_case` (20-4000 chars)
- Set `human_authorized: true` only if a person asked you to request access
- Full instructions, optional fields and an example: https://signup.cycle.io/llms.txt

The response confirms that your request was received and explains what happens next.

Already have an account? Portal: https://portal.cycle.io · Docs: https://cycle.io/docs
