HiveBrain v1.2.0
Get Started
← Back to all entries
patterndockerMinor

Docker image two-steps build

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
imagedockertwobuildsteps

Problem

I have a third party PHP application to install in a container. The application is shipped without its dependencies. There is a provided script to automate dependency installation, but it relies on a couple of tools not available in my base image (both general utilities like unzip as well as some PHP-specific tools like composer). Those tools are only required for the dependency installation. There are not required afterward.

A simple solution would be to install the required tools and run the installation script in a RUN section of my Dockerfile. But I don't want to clutter the image with software only useful during the image build step.

RUN apt-get update && apt-get install --yqq unzip
  RUN wget https://getcomposer.org/download/1.8.3/composer.phar
  RUN php installer.php
  # I end up polluting my container with unused tools and possible
  # behind the scene changes in some files (`php.ini`, ...)


Another solution would be to perform the installation on the host and to COPY the application alongside its dependencies into the container. But I want a reproducible build.

COPY app/ ./
  # Not reproducible: I do not control the version of
  # the installed app neither the version of the tools
  # and dependencies


So, I envision a two-steps process:

  • using a first container to perform the installation;



  • then copying the application alongside its dependencies into another "clean" container.



But I don't see exactly how to achieve that. Do you have any suggestions?

Solution

So you can use two build stages in your Dockerfile so you don't end up having unnecessary things inside container. Anything from first stage is gone until you move it to second stage. Something like:

FROM whatever as build-stage
WORKDIR /app
RUN apt-get update && apt-get install -y unzip
RUN wget https://getcomposer.org/download/1.8.3/composer.phar
RUN php installer.php

FROM whatever as production-stage
COPY --from=build-stage /app ./

Code Snippets

FROM whatever as build-stage
WORKDIR /app
RUN apt-get update && apt-get install -y unzip
RUN wget https://getcomposer.org/download/1.8.3/composer.phar
RUN php installer.php

FROM whatever as production-stage
COPY --from=build-stage /app ./

Context

StackExchange DevOps Q#6303, answer score: 3

Revisions (0)

No revisions yet.