Angular App on Docker

Angular App on Docker







What is covered:
    - how to put angular (2+) app in docker image
What is not covered:
    - angular
    - docker
    - nginx/nginx configurations

Good thing about an angular app is that it is static content. So a docker image would just need alpine image with an nginx server.

How we build it is upto us. We can
Option 1. build on local machine, and then copy built files into docker image.
Option 2. build on a docker image that has sdk, and then deploy on a different docker image.

Option 1 is most tempting.
Option 2 may be right for a production pipeline. Your jenkins (or any CI server) server/nodes may not have an angular sdk installed to build your app. Hence using docker in build pipeline may be useful.

OPTION 1: build on local machine, copy built files into docker image

Creating angular app

Assuming that you have already built your angular app, I will use the one generated by 'ng' itself.
    ng new dockerized-angular-app 

Testing that my app is running
    ng serve

App works. But is not shippable. Lets build it.
    ng build --prod
This command builds static files into "dist" folder.

Dockerizing angular app

Step 1: Use ngingx on alpine as base image because it has smallest signature
Step 2: Copy output of build into "dist"

Dockerfile
    FROM nginx:alpine
    COPY ./dist/dockerized-angular-app/* /usr/share/nginx/html/

Build docker image
    docker build --tag=dockerized-angular-app:v0.0.1 .

Run as container
    docker run -p 80:80 --name dockerized-angular-app dockerized-angular-app:v0.0.1 

Access your app on browser as:

OPTION 2: build and run on docker

With this option, we shall use multi-stage build. We build using 'nodejs' docker image as base. And then we create a separate run image.

Build stage
1. Use nodejs image as base
2. Copy all local files (source files) from current directory into /app directory of image
3. Install angular cli on image
4. Build using angular cli

Runtime image creation
1. Copy all the built files from base image into this image - at location where nginx expects

Dockerfile
FROM node:alpine AS builder

WORKDIR /app

COPY . .

RUN npm install && \
    npm run build && \
    ls /app/dist/dockerized-angular-app

FROM nginx:alpine
COPY --from=builder /app/dist/dockerized-angular-app /usr/share/nginx/html/

Build docker image
    docker build --tag=dockerized-angular-app:v0.0.2 .

Run as container
    docker run -p 80:80 --name dockerized-angular-app dockerized-angular-app:v0.0.2 

Access your app on browser as:





Comments