How to build and run Angular application with Docker
In this article, I'll show you how to create a simple angular application, build it, and then deploy it through a docker image.
Let's create the application
After making sure you have nodejs and npm installed on your pc, let's add angular to our extensions:
npm install -g @angular/cli
at this point we can create our Angular application:
ng new my-app
All the in-depth details are in the official guide.
Let's prepare our conf file for NGINX
To run our application, we will use NGINX server, we will need a configuration file in which to indicate the basic information such as:
- listening port, later used by our container
- server name
- root path, where we will copy our Angular files
This is a simple example `nginx.conf` file below:
events{
http {
include /etc/nginx/mime.types;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
}}
and we can place it in the root of our Angular app.
All the insights on the configuration file are in the official guide.
Now Docker!
We finally got to the point, writing the dockerfile. There are two important steps
- build: build the application to deploy
- deploy: run our app
We can do this in many ways but, in this tutorial we will try to write a single docker file that contains both steps:
### STEP 1: Build ## FROM node:19-alpine AS build WORKDIR /usr/src/app COPY package.json package-lock.json ./ RUN npm install COPY . . RUN npm install -g @angular/cli RUN ng build --configuration production ### STEP 2: Deploy ### FROM nginx:1.23.3-alpine COPY nginx.conf /etc/nginx/nginx.conf COPY --from=build /usr/src/app/dist/my-app /usr/share/nginx/html#
let's place it in the root of our app. We can thus generate our image:
$ docker build -t my-app-image .
and run it:
$ docker run --name my-app-container -d -p 8081:80 my-app-image
our app will be reachable from http://localhost:8081.
As mentioned there are many different ways to achieve the same result, in fact:
this is a trail not a binary