Skip to main content

Publish same Docker image with Angular application to any environments


In this story I would share how to deliver same docker image with angular application inside to any environments.

First of all, we have to create a new application or get an existing one.

By default angular use environment.ts to store configurations for different environment, such as url of backend api. But if we use this approach we have to do different build for each environment (like testing, staging, prod, etc). To avoid multiple build we can use the approach explained in this article.

STEP 1 — Environment variables

As mention before, we can’t use environment.ts to store different values per environments, so let’s create a new file under assets folder called config.json (you can call it whatever you want, but must be a json):

{
"api": "https://local-api.com"
}

Then angular have to get this configuration, to do that I used ReplaySubject in a service. So create new service called config.service.ts and a new model for config property:

export interface ConfigModel {
  api: string;
}

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ReplaySubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { ConfigModel } from 'src/models/config.model';

@Injectable({
  providedIn: 'root',
})
export class ConfigService {
  private configSubject$ = new ReplaySubject<ConfigModel>(1);
  config$ = this.configSubject$.asObservable();
  configSnapshot: ConfigModel;

  constructor(public http: HttpClient) {}

  loadConfig() {
    return this.http.get<ConfigModel>('./assets/config.json').pipe(
      map((config) => {
        this.configSnapshot = config;
        this.configSubject$.next(config);
      })
    );
  }
}

Now let’s call the loadConfig() method on app component and show the model on view:

<ng-container *ngIf="config$ | async as config">
  {{ config.api }}
</ng-container>
import { Component } from '@angular/core';
import { ConfigService } from 'src/services/config.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  config$ = this.configService.config$;

  constructor(private configService: ConfigService) {
    configService.loadConfig().subscribe();
  }
  title = 'angular-docker';
}

Now if we run the application we will see the api url on page:

Image for post
app component

STEP 2 — Create multiple configurations

Now we have to create multiple configurations, one for each environment that you want to manage. For example I created under assets a folder named _environments:

Image for post

config.json files must have the proper configuration of corresponding environment.

Example for Staging:

{
"api": "https://staging-api.com"
}

Example for Production:

{
"api": "https://production-api.com"
}

STEP 3 — Dockerfile

First of all we have to create a new bash file that replace the config file under assets with proper one, based on environment variable (called ENVIRONMENT).

So create new file called 

cp /usr/share/nginx/html/assets/_environments//config.json /usr/share/nginx/html/assets//usr/sbin/nginx -g "daemon off;"
Image for post

After that, we can create new  file on the root as follow:

 node:lts-stretch-slim  builder
package.json package-lock.json ./
npm ci && mkdir /app && cp -R ./node_modules ./app
/app
. .
$(npm bin)/ng build --prod nginx:stable nginx.conf /etc/nginx/conf.d/default.conf rm -rf /usr/share/nginx/html/* --from=builder /app/dist/angular-docker /usr/share/nginx/html ["entrypoint.sh", "/entrypoint.sh"]
["sh", "/entrypoint.sh"]

Let me explain that lines:

  1. STAGE 1: get image of node and name it as builder;
  2. Copy package.json package-lock.json on the root of docker image;
  3. Run npm ci to install dependencies using package-lock.json file;
  4. Copy all source files to app folder inside docker;
  5. Run angular command to build the application in production mode;
  6. STAGE 2: get image from dockerhub nginx:stable;
  7. Copy nginx configuration in default configuration inside nginx server folder;
  8. Copy from previous image (alias builder) the compiled files and put it in root folder of nginx server;
  9. Copy entrypoint.sh to root folder inside docker;
  10. Tell docker to run entrypoint.sh during startup.

STEP 4 — Build the image

In terminal run this command:

docker build -t angular-docker .

to build the image and name it as angular-docker.

Finally, you can run this command to test the application:

docker run -e ENVIRONMENT=Staging -p 5555:80 -it angular-docker:latest

and if you now go to http://localhost:5555 you will see the result:

Image for post

Now if try another command:

docker run -e ENVIRONMENT=Production -p 5556:80 -it angular-docker:latest

you will see correct result:

Image for post

So now you are able to deploy your docker image in any environment, you just have to set the environment variable ENVIRONMENT and the docker image take care of replacing the proper file of configuration.

















































 

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...