To implement multi-stage builds in Docker, follow these steps:
-
Create a Dockerfile: Start by creating a Dockerfile that defines multiple stages. Each stage begins with a
FROMinstruction. -
Define the Build Stage: In the first stage, specify the base image and install any necessary dependencies. You can name this stage using the
ASkeyword. -
Build the Application: In the same stage, compile or build your application.
-
Define the Final Stage: In the next stage, use another
FROMinstruction to specify a lighter base image for the final application. This stage will only include the necessary files from the build stage. -
Copy Artifacts: Use the
COPY --from=<stage_name>command to copy the required files from the build stage to the final stage. -
Set the Command: Specify the command to run your application in the final stage.
Example Dockerfile
# Build stage
FROM python:3.9 AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Final stage
FROM python:3.9-slim
WORKDIR /app
COPY --from=builder /app /app
CMD ["python", "app.py"]
Build the Image
Run the following command in the terminal to build the multi-stage image:
docker build -t multi-stage-app .
Run the Container
After building the image, you can run a container using:
docker run -d -p 5000:5000 --name my-container multi-stage-app
This setup allows you to create a more efficient Docker image by separating the build environment from the runtime environment.
