landing into docker multistage build

When you browse through official docs of docker or few of the videos on youtube. You will find, a single answers from all, multistage will all reduce the complexity and reduce the docker image size. Yes, that is true. Today, I will be talking about what made me utilize the docker multi stage in my Dockerfile.

How many of you have gone through this? The script or codes that were working last time suddenly crashes the next day. I had a Dockerfile build with alpine as base image. It was working like a charm. After running the same Dockerfile now, It was throwing errors on installing the composer. I know, installing the composer is just one line to add but every effort I put on was into vein. The only option left for me was to add composer separately or use already successfully running composer.

I tried it and was working like a charm again. So initially I deleted the line which was to add composer in my Dockerfile: which was a main culprit. Than added the composer in the first line of the Dockerfile as shown bellow.

FROM composer:1.5.1 AS my_composer

This line will simply add the docker image with composer. I added this because this had the composer installed in alpine os.

Now time to add my real alpine image that I was using and that had the trouble.

FROM alpine:3.8

So now we have a Two FROM here, which is why we call it multistage docker.

Now time to add the composer from first image to the second. Which can be easily done as bellow.

COPY --from=my_composer /usr/bin/composer  /usr/bin/composer

This will copy the /usr/bin/composer from first composer image to the second alpine image. We use –from to specify from where to copy. The first argument is the source and second being the destination.

So I build the image again. It worked flawless. But most of you might have the issue like php not found. This is because the php path is not set in the second image so need to set it. I just added a symlink for the solution as follow.

RUN ls -s /usr/bin/php7  /usr/bin/php

Though, this article does not describe about how to use multistage docker. I hope, putting my real experience might have even helped better to realize when do we really need it. In future I will try to put on some easy materials too, regarding how to add or write multi stage docker file.

Leave a Reply