DEV Community

Pavan K Jadda for This is Angular

Posted on

Multi Stage Docker builds with Angular and Nginx

This blog post shows multi stage Dockerfile that builds and deploys Angular app in Nginx container


The above Dockerfile has 2 stages
  • Stage 1 - Install NPM dependencies and builds Angular project

  • Stage 2 - Builds docker image from dist directory generated by previous stage

Stage 1: Install dependencies and Build Angular project

  • We use Node 16 alpine image to build the project and it accepts CONFIGURATION build argument. You can override this during build based on your environment
docker build --build-arg CONFIGURATION=dev .
Enter fullscreen mode Exit fullscreen mode

and you can also define as many arguments as you like

  • Then make /app as working directory. All of the source code and files will be copies to /app directory inside Node container
WORKDIR /app
Enter fullscreen mode Exit fullscreen mode
  • Copy the package.json file to /app directory. This will enable Docker to cache the node_modules rather than building from scratch and sub sequent builds use these when package.json file is unchanged.
COPY package.json .
Enter fullscreen mode Exit fullscreen mode
  • Install dependencies using npm install command and specify flag —-legacy-peer-deps to prevent build errors in NPM 7+
RUN npm install --legacy-peer-deps
Enter fullscreen mode Exit fullscreen mode
  • Then copy the source code and build the project using npm run build
COPY . .
RUN npm run build --  --output-path=dist --configuration=$CONFIGURATION --output-hashing=all
Enter fullscreen mode Exit fullscreen mode
  • The built code will be present in /app/dist directory in Node container

Stage 2: Build Docker image

  • We use NgInx alpine stable image to serve Angular application in production

  • Remove existing HTML content using the command

RUN rm -rf /usr/share/nginx/html/*
Enter fullscreen mode Exit fullscreen mode
  • Copy the Nginx config file from source to /etc/nginx/nginx.conf directory. If you don’t have one, you can use the below one
  • Then Copy dist folder from build stage to nginx public folder
COPY — from=builder /app/dist /usr/share/nginx/html
Enter fullscreen mode Exit fullscreen mode
  • At the end specify the NgInx start command. That’s it.

You can also split Stage 1 into two separate stages. One to install dependencies and the second one to build the Angular app :)

Top comments (0)