How to implement multi-stage builds?

0152

To implement multi-stage builds in Docker, follow these steps:

  1. Create a Dockerfile: Start by creating a Dockerfile that defines multiple stages. Each stage begins with a FROM instruction.

  2. Define the Build Stage: In the first stage, specify the base image and install any necessary dependencies. You can name this stage using the AS keyword.

  3. Build the Application: In the same stage, compile or build your application.

  4. Define the Final Stage: In the next stage, use another FROM instruction to specify a lighter base image for the final application. This stage will only include the necessary files from the build stage.

  5. Copy Artifacts: Use the COPY --from=<stage_name> command to copy the required files from the build stage to the final stage.

  6. 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.

0 Comments

no data
Be the first to share your comment!