Dockerize your Angular Application
Angular is a popular and powerful front-end framework for building enterprise-grade applications.
In this article, I will show you how you can easily create a docker image of your Angular application. Some of the reasons you might want to do this are:
- To deploy your Angular application as a service
- To easily share your application with other developers and
- To easily run the application in other environments without being concerned about installing application dependencies
Create an Angular application
You can create an Angular application using the Angular CLI, simply run the following command:
$ ng new angular-docker --style==scss --routing=true
Add a Dockerfile
Add a file named Dockerfile to the root of your newly created angular project. Note: the file has no extension.
$ touch Dockerfile
A Dockerfile contains instructions for building the docker image and also defines an entry point for executing the container, i.e. a running instance of the image.
Now, copy the lines of code below and paste into your newly created Dockerfile.
FROM node:10.21.0-alpine as builder
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build --prodFROM nginx:1.16.0-alpine as server
COPY --from=builder /app/dist/angular-docker /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]
Build the Docker image
We can now build our docker image based on the Dockerfile above. Simply run the following command from the projects’ root folder.
$ docker build -t angular-docker -f Dockerfile .
The -t angular-docker option tags our Docker image with the name angular-docker.
List Docker images
After the image is finalized building you can list available Docker images on your system and you will get an output similar to the one below.
$ docker images
Run the Docker image
To run the newly created image, simply run the command below, where angular-docker is the name of your Docker image.
$ docker run -ti --rm -p 8080:80 angular-docker
We have specified that the Docker image should run on the HTTP port 8080 of the local PC which maps to port 80 inside the Docker image.
Go the link http:localhost:8080/ in your browser and there you will find your Angular application running as a docker container as below: