I recently had the challenge of running an Angular application in a Kubernetes cluster. This means running the Angular application in a Docker container. We wanted to make it self contained, so the the docker image has to have its own webserver, but at the same time be lightweight.

We chose to base our Docker image on the Nginx webserver, for it’s ease of use and lightweight nature. It turns out there is an official docker image for Nginx, so we can base our image on this to get Nginx out of the box. We created a Dockerfile and started it with the following line:

FROM nginx:latest

Next we need to configure Nginx to work properly with Angular. Angular relies on the webserver redirecting any error pages (in particular 404 errors) to the index.html file. This enables Angular to handle routing based on the URL without the path actually existing on the server. We can configure Nginx to do this in our nginx.conf file. Let’s create the file in the same directory as the Dockerfile:

server {
  listen 80;
  charset utf-8;
  sendfile on;
  root /usr/share/nginx/html;
   
  location / {
    expires -1;
    add_header Pragma "no-cache";
    add_header Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
  
    try_files $uri $uri/ /index.html = 404;
  }  
}

Now we need to include the config file in our Docker image with the following line in our Dockerfile:

COPY nginx.conf /etc/nginx/conf.d/default.conf

Finally and most importantly, we need to include our Angular app in the Docker image. This is done by copying the contents of the dist folder, generated when building angular, into the Nginx root path. In the nginx.conf file we configured the root to be /usr/share/nginx/html, so this is the path we will copy our Angular app to. Add the final line of the Dockerfile:

COPY dist/app /usr/share/nginx/html

As you can see, I copy the contents of the app folder inside the dist folder. This is the location that my Angular project is set up to output at. You should copy the contents of the directory containing the index.html file.

This is all you need to dockerize your Angular app. Now in order to create a container with your Angular app, you would first build your Angular app using something like:

ng build --prod

And then create a container from that:

docker build -t angular-app .