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.

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',
};

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

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;'"]

Build your project:

$ ng build

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

$ docker build -t angular/your-app-name .

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

30