angular docker

·

3 min read

What is Docker

Docker is a popular open-source project works as a container engine that uses the Linux Kernel features like namespaces and control groups to create containers on top of an operating system. By using docker we can package our applications into container.

We are creating angular Docker image so that we need following software's installed in our system

  • Node JS
  • Docker
  • Angular CLI

First step is to create new angular application using below command

ng new angulardockerapp

Next command would be

ng serve -o

Our angular application default page will look like below:

angular app default page.png

Now add a Dockerfile in the application root without any file extension 'Dockerfile' and write some executables scripts:

### STAGE 1: Build ###
FROM node:14.15.2-alpine AS builder
WORKDIR /DockerAngularApp
COPY package.json package-lock.json ./
RUN npm i
COPY . .
RUN npm run build --prod

### STAGE 2: Run ###
FROM nginx:1.19.1-alpine
COPY  --from=builder /DockerAngularApp/dist/docker-angular-app /usr/share/nginx/html

The first command call the Docker to pull the node image with tag 14.15.2-alpine.

WORKDIR command set the working directory in our docker image: any command further will be run in its context.

COPY will copy package.json and package-lock.json to the root of our working directory, inside a container.

execute npm install command to download all the dependencies from the package.json file

COPY all the files to the working directory to execute the npm build --prod command.

stage 2

using FROM statement we are specifying that we want to use nginx.

copy statement will copy Angular app from working directory /DockerAngularApp/dist folder in the builderapp to the nginx html folder.

Now Dockerfile all set. We need to create a docker image using below command

docker build -t angular-docker-app .

Now it's time to execute docker container

docker run --name angular-docker-app -d -p 5555:80 angular-docker-app

open your browser and run localhost:5555 your angular image will execute without any hassle

Now push docker image to docker hub

docker tag angular-docker-app:v1 codewithashish/angularapp:angular-docker-app

here we are creating tag with the version 1. Here codewithashish is a docker id, angularapp is a repository

Now push docker image to docker hub

docker push codewithashish/angularapp:angular-docker-app