Mini Builds

Angular + Nginx + Docker

March 25, 2021

In this article we are going to Dockerise an Angular app that uses routing using Nginx to handle mapping routes.

Checkout the complete project on GitHub: https://github.com/mini-builds/angular-nginx-docker

Angular

Create a new Angular project with Angular routing enable, ng new angular-nginx-docker. Next create a few pages (main page, java page, python page, and rust page) using ng generate component .... The main page contains links to each of the languages and the language pages contains hello world examples.

Nginx

Create a file called nginx.conf (in the root of the Angular project) with the contents below. This config tells nginx to:

server {
    listen 80;
    listen [::]:80;

    root /usr/share/nginx/html;

    index index.html;

    location / {
        root /usr/share/nginx/html;
        try_files $uri $uri/ /index.html;
    }
}

Docker

Create a file called Dockerfile (in the root of the Angular project) with the contents below. This Dockerfile contains commands to create our docker image:

FROM nginx

COPY ./dist/angular-nginx-docker /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/conf.d/default.conf

Putting everything together

To tie everything together we:

  1. Build the Angular app.
  2. Build the Docker image.
  3. Run the Docker container.
ng build --prod

docker build . -t minibuilds.io/angular-nginx-docker

docker run --rm -p 80:80 minibuilds.io/angular-nginx-docker

We should now have container listening on port 80 serving out Angular app. Navigate to http://localhost/ to see it in action.