DEV Community

Cover image for Create one Docker image of Angular + Nginx with dynamic API url
Felipe Henrique Gross Windmoller
Felipe Henrique Gross Windmoller

Posted on

Create one Docker image of Angular + Nginx with dynamic API url

In this tutorial, I explain one workaround that I did to create one Docker image of one Angular application which has one dynamic API URL.

The article How To Build An Angular App Once And Deploy It To Multiple Environments - Solution 4: Override environment file values explains how you can do this.

But, as I'm far from a Docker expert, I spent some time to create the Dockerfile to do this :)

Just quoting the article:

The idea is to use Angular’s environment.ts (for local development) and environment.prod.ts (for all other stages) with placeholder values which are overwritten per deployment:

export const environment = {
  apiUrl: 'MY_APP_API_URL',
  stage: 'MY_APP_STAGE',
};
Enter fullscreen mode Exit fullscreen mode

If our pod is started we can then run the following script, for example in a Dockerfile, that overrides these placeholder values:

#!/bin/sh
# replace placeholder value in JS bundle with environment specific values
sed -i "s#MY_APP_API_URL#$API_URL#g" /usr/share/nginx/html/main.*.js
Enter fullscreen mode Exit fullscreen mode

My contribution

Here is the Dockerfile I created to run this workaround:

FROM nginx:latest

COPY dist/your-app-name /usr/share/nginx/html

CMD ["/bin/bash", "-c", \
"echo API_URL=[$API_URL], && \
sed -i s#MY_APP_API_URL#$API_URL#g /usr/share/nginx/html/main.*.js && \
nginx -g 'daemon off;'"]
Enter fullscreen mode Exit fullscreen mode

Build your project:

$ ng build
Enter fullscreen mode Exit fullscreen mode

Place this Dockerfile into your Angular root folder and run this to build your image:

$ docker build -t angular/your-app-name .
Enter fullscreen mode Exit fullscreen mode

After this, just run your container passing the API_URL variable:

$ docker run -p 80:80 --name your-app-name -e API_URL=http://localhost:8080 angular/your-app-name
Enter fullscreen mode Exit fullscreen mode

Latest comments (3)

Collapse
 
kavinda1995 profile image
Kavinda Jayakody

Great article! Thanks man <3

Collapse
 
marcuspaulo profile image
Marcus Paulo

Parabéns Felipão, excelente artigo.

Collapse
 
felipewind profile image
Felipe Henrique Gross Windmoller

Muito obrigado Marcus!!!