Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Combine multiple images using one dockerfile
When you are working on a large project with Docker, you need to go through certain phases of the development cycle. Maintaining a different dockerfile for each cycle such as build, release, testing etc. consumes significant resources and reduces productivity efficiency.
In later versions of Docker, multi-stage Dockerfile functionality allows us to use multiple images in a single Dockerfile with the help of two particular commands − FROM and AS.
How Multi-Stage Dockerfiles Work
We can use multiple FROM commands combined with AS commands in our Dockerfile where the last FROM command builds the final image. All the FROM commands before that create intermediate images which are cached regularly.
The AS command when used with the FROM command allows us to provide a virtual name for our intermediate images, making them referenceable in later stages.
Multi-Stage Dockerfile Structure
Example Multi-Stage Dockerfile
# We create a base image FROM ubuntu AS base # Install packages RUN apt-get -y update RUN apt-get -y install vim # Create intermediate image layer Dependencies FROM base AS dependencies # Install dependencies using a requirements file RUN pip3 install -r requirements.txt # Create intermediate image layer for Testing FROM dependencies AS test # Set your work directory WORKDIR /usr/src/app COPY . . # Build the final image by running the test file CMD ["python3", "./test.py"]
Stage Breakdown
| Stage | Purpose | Commands |
|---|---|---|
| base | Foundation layer with OS updates | Update packages, install vim editor |
| dependencies | Install project dependencies | Install packages from requirements.txt |
| test | Final application layer | Set workdir, copy files, define CMD |
Key Points
The build order is sequential − base, then dependencies, and finally test.
If any intermediate image fails to build, the final image cannot be created.
Intermediate images are cached, improving build performance on subsequent runs.
Each stage can reference previous stages using their
ASnames.
Advantages
Resource Efficiency − Single Dockerfile manages multiple build phases
Better Caching − Intermediate layers are cached and reused
Organized Development − Clear separation of build, test, and deployment phases
Reduced Image Size − Final image contains only necessary components
Conclusion
Multi-stage Dockerfiles provide an efficient way to manage complex application builds by combining multiple images into a single Dockerfile. This approach improves resource utilization, enables better caching, and provides clear separation of development phases for large-scale projects.
