DockerFile — Multiple Stage build

How To Dockerize an Angular Application with multistage build

  • A multistage build allows you to use multiple images to build a final product.
  • In a multi-stage build, you have a single Dockerfile but can define multiple images inside it to help build the final image.
  • This approach to keeping Docker images small is using multistage builds

Let’s try to understand the multi-stage docker file that you can find in the below GitHub page.

Clone the sample angular code

git clone https://github.com/DenysVuika/medium-angular-docker.git

You will see a DockerFile with the below content.

# Step 1: Build the app in image 'builder'
FROM node:12.8-alpine AS builder
# Set the working directory
WORKDIR /usr/src/app
# Add the source code to app
COPY . .
# Generate the build of the application
RUN yarn && yarn build
# Step 2: Use build output from 'builder'
FROM nginx:stable-alpine
# Use Labels for organize Docker Images
LABEL version="1.0"
# Add the nginx.conf file
COPY nginx.conf /etc/nginx/nginx.conf
# Set the working directory
WORKDIR /usr/share/nginx/html
# Copy the build output to replace the default nginx contents
COPY --from=builder /usr/src/app/dist/my-angular-app/ .

This Dockerfile has two stages.

Stage 1:

  • It will initialize a first build stage and this stage is named as build.
  • Angular build in a new layer on top of the base node image. After this instruction is executed, the build output is stored under usr/local/app/dist/my-angular-app

Stage 2:

  • Initializes a secondary build stage
  • Copies the build output generated in stage 1 (--from=build) to replace the default Nginx contents in this path -/usr/share/nginx/html.

Now, let’s build a docker image and run a container

$ docker build -t angular:v1.0.0 .
$ docker run -d -p 80:80 --name angular-app angular:v1.0.0

Test the application

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store