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:
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:
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).
If you are running on windows machine, pay attention of format of file on bottom right of vscode editor:
After that, we can create new Dockerfile file on the root as follow:
### STAGE 1: Build ### FROM node:lts-stretch-slim as builder COPY package.json package-lock.json ./## Storing node modules on a separate layer will prevent unnecessary npm installs at each build RUN npm ci && mkdir /app && cp -R ./node_modules ./app WORKDIR /app COPY . .## Build the angular app in production mode and store the artifacts in dist folder RUN $(npm bin)/ng build --prod### STAGE 2: Setup ### FROM nginx:stable## Copy our default nginx config COPY nginx.conf /etc/nginx/conf.d/default.conf## Remove default nginx website RUN rm -rf /usr/share/nginx/html/*## From 'builder' stage copy over the artifacts in dist folder to default nginx public folder COPY --from=builder /app/dist/angular-docker /usr/share/nginx/htmlCOPY ["entrypoint.sh", "/entrypoint.sh"] CMD ["sh", "/entrypoint.sh"]
Let me explain that lines:
STAGE 1: get image of node and name it as builder;
Copy package.json package-lock.json on the root of docker image;
Run npm ci to install dependencies using package-lock.json file;
Copy all source files to app folder inside docker;
Run angular command to build the application in production mode;
STAGE 2: get image from dockerhub nginx:stable;
Copy nginx configuration in default configuration inside nginx server folder;
Copy from previous image (alias builder) the compiled files and put it in root folder of nginx server;
Copy entrypoint.sh to root folder inside docker;
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
docker run -e ENVIRONMENT=Production -p 5556:80 -it angular-docker:latest
you will see correct result:
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.
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...
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...
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...
Comments
Post a Comment