In this write up we’ll see how to dockerize an Angular app in an efficient manner with Docker’s Multi-Stage Builds.
At the time of writing this post, I'm using Angular v7
- NodeJS +8
- Angular CLI (
npm i -g @angular/cli@latest)
- Docker +17.05
- Basic understanding of Docker and Angular CLI commands
To dockerize a basic Angular app built with Angular CLI, we need to do the following:
- npm install the dependencies (dev dependencies included)
- ng build with --prod flag
- move the artifacts from
distfolder to a publicly accessible folder (via an an nginx server)
- Setup an nginx config file, and spin up the http server
We’ll do this in 2 stages:
- Build stage: will depend on a Node alpine Docker image
- Setup stage: will depend on NGINX alpine Docker image and use the artifacts from the build stage, and the nginx config from our project.
$ ng new myapp
At the root of your Angular project, create nginx folder and create a file named default.conf with the following contents (./nginx/default.conf):
### STAGE 1: Build ### # We label our stage as ‘builder’ FROM node:10-alpine as builder COPY package.json package-lock.json ./ ## Storing node modules on a separate layer will prevent unnecessary npm installs at each build RUN npm ci && mkdir /ng-app && mv ./node_modules ./ng-app WORKDIR /ng-app COPY . . ## Build the angular app in production mode and store the artifacts in dist folder RUN npm run ng build -- --prod --output-path=dist ### STAGE 2: Setup ### FROM nginx:1.14.1-alpine ## Copy our default nginx config COPY nginx/default.conf /etc/nginx/conf.d/ ## Remove default nginx website RUN rm -rf /usr/share/nginx/html/* ## From ‘builder’ stage copy over the artifacts in dist folder to default nginx public folder COPY --from=builder /ng-app/dist /usr/share/nginx/html CMD ["nginx", "-g", "daemon off;"]
$ docker build -t myapp .
$ docker run -p 8080:80 myapp
And done, your dockerized app will be accessible at http://localhost:8080
And the size of the image is only ~15.8MB, which will be even less once pushed to a Docker repository.
You can see a full example in this GitHub repository: https://github.com/avatsaev/angular-contacts-app-example