SlideShare a Scribd company logo
1 of 36
Download to read offline
BioBio
Software Engineer @ Container Solutions
Full-stack developer but mostly backend
Passionate about architecture and
infrastructure
❤ containers
Deploying con gurable frontend web application
containers
AgendaAgenda
Deploying backend containers
Web application con guration
Meta tags approach
Application level code
Deployment scripts
Kubernetes deployment
Local development
environment
Demo
Questions?
My experiences deploying webMy experiences deploying web
applicationsapplications
Deploying backend containersDeploying backend containers
# docker-compose.yaml
version: '3'
services:
backend:
image: example/api:latest
ports:
- "8080:8080"
environment:
- DB_USER=user
- DB_PASS=secret_password
- DB_NAME=exampledb
depends_on:
- db
db:
image: sameersbn/postgresql:10
ports:
- "5432:5432"
environment:
- DB_USER=user
- DB_PASS=secret_password
- DB_NAME=exampledb
Docker imagesDocker images
Build once, run anywhere
Treating frontend containersTreating frontend containers
like backend containerslike backend containers
How client-side applicationsHow client-side applications
workwork
Runtime is the client Web browser
Client-side applications cannot read environment
variables or con guration les
Source code is bundled and served from CDN or
application web servers
Con guration values are “hardcoded” at build time
Webpack asset build
Web Application con gurationWeb Application con guration
pointspoints
Con guration values change per environment
(development, staging, production):
API URLs
API tokens
Analytics tracking codes (client
IDs)
Application parameters
Deploying web applicationDeploying web application
with containerswith containers
Some approaches to con guration per environment
Docker leDocker le
FROM node:8.11.4-jessie
RUN mkdir /app
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
ENV NODE_ENV production
RUN npm run build
CMD npm run dev
Rebuild assets beforeRebuild assets before
deployment (inside Dockerdeployment (inside Docker
container)container)
Adds to deployment time. Depending on deployment
rate and size of the project, the deployment time
overhead might be considerable.
Is prone to build failures at end of deployment pipeline
(network conditions)
Might a ect rollback speed
Build one image perBuild one image per
environmentenvironment
Adds clutter to the docker registry/daemon.
Changing con guration implies rebuilding Docker
images
Loading con g from HTTPLoading con g from HTTP
endpointendpoint
Web app requests con guration from a dynamically
generated https://myapp.com/js/config.js le.
Extra request per page load implies higher tra c load
Web app cannot start business logic before loading
con guration
Meta tags approachMeta tags approach
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1
<meta property="DOOM_STATE_SERVICE_URL" content="http://localhost
<meta property="DOOM_ENGINE_SERVICE_URL" content="http://localhos
<link rel="icon" href="./favicon.ico">
<title>frontend</title>
</head>
<body>
<noscript>
<strong>We're sorry but frontend doesn't work properly without
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
Con guration meta tags are added to index.html
During deployment, meta tag values are rewritten based
on environment variables (or mounted con guration
les)
Javascript application reads con guration from meta
tags on page load
Abstracting the con gurationAbstracting the con guration
layerlayer
$ cat src/config/loader.js
/**
*
* Get config value with precedence:
* - check `process.env`
* - check current web page meta tags
* @param {string} key Configuration key name
*/
function getConfigValue (key) {
let value = null
if (process.env && process.env[`${key}`] !== undefined) {
// get env var value
value = process.env[`${key}`]
} else {
// get value from meta tag
return getMetaValue(key)
}
return value
}
// ommited rest of code
$ cat src/config/index.js
anywhere on the source code
import loader from './loader'
export default {
DOOM_STATE_SERVICE_URL: loader.getConfigValue('DOOM_STATE_SERVICE_U
DOOM_ENGINE_SERVICE_URL: loader.getConfigValue('DOOM_ENGINE_SERVICE
}
import config from './config'
console.log(config.DOOM_ENGINE_SERVICE_URL)
Kubernetes deploymentKubernetes deployment
Deployment helper script:
Deletes existing les from public directory
Copies dist assets from Docker image to public
directory
Rewrites con g meta tags on public directory
index.html
$cat bin/rewrite-config.js
#!/usr/bin/env node
const cheerio = require('cheerio')
const copy = require('recursive-copy')
const fs = require('fs')
const rimraf = require('rimraf')
const DIST_DIR = process.env.DIST_DIR
const WWW_DIR = process.env.WWW_DIR
const DOOM_STATE_SERVICE_URL = process.env.DOOM_STATE_SERVICE_URL
const DOOM_ENGINE_SERVICE_URL = process.env.DOOM_ENGINE_SERVICE_URL
// ommited rest of code
Kubernetes deploymentKubernetes deployment
manifestmanifest
Kubernetes init containerKubernetes init container
initContainers:
- name: doom-client
image: "doom-client:latest"
command: ["/app/bin/rewrite-config.js"]
imagePullPolicy: IfNotPresent
env:
- name: DIST_DIR
value: "/app/dist"
- name: WWW_DIR
value: "/tmp/www"
- name: DOOM_ENGINE_SERVICE_URL
value: "http://localhost:8081/"
- name: DOOM_STATE_SERVICE_URL
value: "http://localhost:8082/"
volumeMounts:
- name: www-data
mountPath: /tmp/www
Kubernetes ContainerKubernetes Container
containers:
- name: nginx
image: nginx:1.14
imagePullPolicy: IfNotPresent
volumeMounts:
- name: www-data
mountPath: /usr/share/nginx/html
- name: doom-client-nginx-vol
mountPath: /etc/nginx/conf.d
Kubernetes shared persistentKubernetes shared persistent
volumevolume
volumes:
- name: www-data
emptyDir: {}
- name: doom-client-nginx-vol
configMap:
name: doom-client-nginx
Local developmentLocal development
environmentenvironment
Docker Compose services:
webpack dev server
backend API services
NGINX instance for production build
testing
UI service (webpackUI service (webpack
dev server)dev server)
version: '3'
services:
ui:
build: .
command: ["npm", "run", "dev", ]
ports:
- "8080:8080"
environment:
- HOST=0.0.0.0
- PORT=8080
- NODE_ENV=development
- DOOM_ENGINE_SERVICE_URL=http://localhost:8081/
- DOOM_STATE_SERVICE_URL=http://localhost:8082/
volumes:
- .:/app
# bind volume inside container for source mount not shadow image d
- /app/node_modules
- /app/dist
Backend servicesBackend services
doom-engine:
image: microservice-doom/doom-engine:latest
environment:
- DOOM_STATE_SERVICE_URL=http://doom-state:8080/
- DOOM_STATE_SERVICE_PASSWORD=enginepwd
ports:
- "8081:8080"
doom-state:
image: microservice-doom/doom-state:latest
ports:
- "8082:8080"
Production build test servicesProduction build test services
ui-deployment:
build: .
command: ["/app/bin/rewrite-config.js"]
environment:
- NODE_ENV=production
- DIST_DIR=/app/dist
- WWW_DIR=/tmp/www
- DOOM_ENGINE_SERVICE_URL=http://localhost:8081/
- DOOM_STATE_SERVICE_URL=http://localhost:8082/
volumes:
- .:/app
# bind volume inside container for source mount not shadow image d
- /app/node_modules
- /app/dist
# shared NGINX static files dir
- www-data:/tmp/www
depends_on:
- nginx
Test production build withTest production build with
NGINXNGINX
nginx:
image: nginx:1.14
ports:
- "8090:80"
volumes:
- www-data:/usr/share/nginx/html
# shared persistent volume
volumes:
www-data:
DemoDemo
Shameless plugShameless plug
https://container-solutions.com/deploying-con gurable-
frontend-web-application-containers/
Keep in touch!Keep in touch!
Twitter: @zemanel
E-mail: jose.moreira@container-solutions.com
LinkedIn:
https://www.linkedin.com/in/josemoreira
QuestionsQuestions

More Related Content

What's hot

What's hot (20)

Running Docker in Development & Production (#ndcoslo 2015)
Running Docker in Development & Production (#ndcoslo 2015)Running Docker in Development & Production (#ndcoslo 2015)
Running Docker in Development & Production (#ndcoslo 2015)
 
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
 
Configuring Django projects for multiple environments
Configuring Django projects for multiple environmentsConfiguring Django projects for multiple environments
Configuring Django projects for multiple environments
 
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
 
ApacheConNA 2015: What's new in Apache httpd 2.4
ApacheConNA 2015: What's new in Apache httpd 2.4ApacheConNA 2015: What's new in Apache httpd 2.4
ApacheConNA 2015: What's new in Apache httpd 2.4
 
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHPHands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
 
kubernetes practice
kubernetes practicekubernetes practice
kubernetes practice
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)
 
Drone CI/CD 自動化測試及部署
Drone CI/CD 自動化測試及部署Drone CI/CD 自動化測試及部署
Drone CI/CD 自動化測試及部署
 
Deployment Tactics
Deployment TacticsDeployment Tactics
Deployment Tactics
 
Gradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forGradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting for
 
Introduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript ConferenceIntroduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript Conference
 
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agentsPVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
PVS-Studio: analyzing pull requests in Azure DevOps using self-hosted agents
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 
Lessons from running potentially malicious code inside Docker containers
Lessons from running potentially malicious code inside Docker containersLessons from running potentially malicious code inside Docker containers
Lessons from running potentially malicious code inside Docker containers
 
Statyczna analiza kodu PHP
Statyczna analiza kodu PHPStatyczna analiza kodu PHP
Statyczna analiza kodu PHP
 
Express js
Express jsExpress js
Express js
 
Single Page Applications in Drupal
Single Page Applications in DrupalSingle Page Applications in Drupal
Single Page Applications in Drupal
 

Similar to Deploying configurable frontend web application containers

Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018
Ortus Solutions, Corp
 
[convergese] Adaptive Images in Responsive Web Design
[convergese] Adaptive Images in Responsive Web Design[convergese] Adaptive Images in Responsive Web Design
[convergese] Adaptive Images in Responsive Web Design
Christopher Schmitt
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
svilen.ivanov
 

Similar to Deploying configurable frontend web application containers (20)

Rails Engine | Modular application
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular application
 
Infrastructure = code - 1 year later
Infrastructure = code - 1 year laterInfrastructure = code - 1 year later
Infrastructure = code - 1 year later
 
Deploying windows containers with kubernetes
Deploying windows containers with kubernetesDeploying windows containers with kubernetes
Deploying windows containers with kubernetes
 
Docker Compose Explained
Docker Compose ExplainedDocker Compose Explained
Docker Compose Explained
 
Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018
 
Nats meetup oct 2016 docker 112
Nats meetup oct 2016 docker 112Nats meetup oct 2016 docker 112
Nats meetup oct 2016 docker 112
 
Amazon Web Services and Docker: from developing to production
Amazon Web Services and Docker: from developing to productionAmazon Web Services and Docker: from developing to production
Amazon Web Services and Docker: from developing to production
 
Microservices DevOps on Google Cloud Platform
Microservices DevOps on Google Cloud PlatformMicroservices DevOps on Google Cloud Platform
Microservices DevOps on Google Cloud Platform
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
[convergese] Adaptive Images in Responsive Web Design
[convergese] Adaptive Images in Responsive Web Design[convergese] Adaptive Images in Responsive Web Design
[convergese] Adaptive Images in Responsive Web Design
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
 
Making a small QA system with Docker
Making a small QA system with DockerMaking a small QA system with Docker
Making a small QA system with Docker
 
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R..."Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Docker Security workshop slides
Docker Security workshop slidesDocker Security workshop slides
Docker Security workshop slides
 
ContainerDayVietnam2016: Docker for JS Developer
ContainerDayVietnam2016: Docker for JS DeveloperContainerDayVietnam2016: Docker for JS Developer
ContainerDayVietnam2016: Docker for JS Developer
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
 
Write php deploy everywhere
Write php deploy everywhereWrite php deploy everywhere
Write php deploy everywhere
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

Deploying configurable frontend web application containers

  • 1. BioBio Software Engineer @ Container Solutions Full-stack developer but mostly backend Passionate about architecture and infrastructure ❤ containers
  • 2. Deploying con gurable frontend web application containers
  • 3. AgendaAgenda Deploying backend containers Web application con guration Meta tags approach Application level code Deployment scripts Kubernetes deployment Local development environment Demo Questions?
  • 4. My experiences deploying webMy experiences deploying web applicationsapplications
  • 5. Deploying backend containersDeploying backend containers # docker-compose.yaml version: '3' services: backend: image: example/api:latest ports: - "8080:8080" environment: - DB_USER=user - DB_PASS=secret_password - DB_NAME=exampledb depends_on: - db db: image: sameersbn/postgresql:10 ports: - "5432:5432" environment: - DB_USER=user - DB_PASS=secret_password - DB_NAME=exampledb
  • 6. Docker imagesDocker images Build once, run anywhere
  • 7. Treating frontend containersTreating frontend containers like backend containerslike backend containers
  • 8. How client-side applicationsHow client-side applications workwork Runtime is the client Web browser Client-side applications cannot read environment variables or con guration les Source code is bundled and served from CDN or application web servers Con guration values are “hardcoded” at build time
  • 10. Web Application con gurationWeb Application con guration pointspoints Con guration values change per environment (development, staging, production): API URLs API tokens Analytics tracking codes (client IDs) Application parameters
  • 11. Deploying web applicationDeploying web application with containerswith containers Some approaches to con guration per environment
  • 12. Docker leDocker le FROM node:8.11.4-jessie RUN mkdir /app WORKDIR /app COPY package.json . RUN npm install COPY . . ENV NODE_ENV production RUN npm run build CMD npm run dev
  • 13. Rebuild assets beforeRebuild assets before deployment (inside Dockerdeployment (inside Docker container)container) Adds to deployment time. Depending on deployment rate and size of the project, the deployment time overhead might be considerable. Is prone to build failures at end of deployment pipeline (network conditions) Might a ect rollback speed
  • 14. Build one image perBuild one image per environmentenvironment Adds clutter to the docker registry/daemon. Changing con guration implies rebuilding Docker images
  • 15. Loading con g from HTTPLoading con g from HTTP endpointendpoint Web app requests con guration from a dynamically generated https://myapp.com/js/config.js le. Extra request per page load implies higher tra c load Web app cannot start business logic before loading con guration
  • 16. Meta tags approachMeta tags approach <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1 <meta property="DOOM_STATE_SERVICE_URL" content="http://localhost <meta property="DOOM_ENGINE_SERVICE_URL" content="http://localhos <link rel="icon" href="./favicon.ico"> <title>frontend</title> </head> <body> <noscript> <strong>We're sorry but frontend doesn't work properly without </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
  • 17. Con guration meta tags are added to index.html During deployment, meta tag values are rewritten based on environment variables (or mounted con guration les) Javascript application reads con guration from meta tags on page load
  • 18. Abstracting the con gurationAbstracting the con guration layerlayer
  • 19. $ cat src/config/loader.js /** * * Get config value with precedence: * - check `process.env` * - check current web page meta tags * @param {string} key Configuration key name */ function getConfigValue (key) { let value = null if (process.env && process.env[`${key}`] !== undefined) { // get env var value value = process.env[`${key}`] } else { // get value from meta tag return getMetaValue(key) } return value } // ommited rest of code
  • 20. $ cat src/config/index.js anywhere on the source code import loader from './loader' export default { DOOM_STATE_SERVICE_URL: loader.getConfigValue('DOOM_STATE_SERVICE_U DOOM_ENGINE_SERVICE_URL: loader.getConfigValue('DOOM_ENGINE_SERVICE } import config from './config' console.log(config.DOOM_ENGINE_SERVICE_URL)
  • 21. Kubernetes deploymentKubernetes deployment Deployment helper script: Deletes existing les from public directory Copies dist assets from Docker image to public directory Rewrites con g meta tags on public directory index.html
  • 22. $cat bin/rewrite-config.js #!/usr/bin/env node const cheerio = require('cheerio') const copy = require('recursive-copy') const fs = require('fs') const rimraf = require('rimraf') const DIST_DIR = process.env.DIST_DIR const WWW_DIR = process.env.WWW_DIR const DOOM_STATE_SERVICE_URL = process.env.DOOM_STATE_SERVICE_URL const DOOM_ENGINE_SERVICE_URL = process.env.DOOM_ENGINE_SERVICE_URL // ommited rest of code
  • 24. Kubernetes init containerKubernetes init container initContainers: - name: doom-client image: "doom-client:latest" command: ["/app/bin/rewrite-config.js"] imagePullPolicy: IfNotPresent env: - name: DIST_DIR value: "/app/dist" - name: WWW_DIR value: "/tmp/www" - name: DOOM_ENGINE_SERVICE_URL value: "http://localhost:8081/" - name: DOOM_STATE_SERVICE_URL value: "http://localhost:8082/" volumeMounts: - name: www-data mountPath: /tmp/www
  • 25. Kubernetes ContainerKubernetes Container containers: - name: nginx image: nginx:1.14 imagePullPolicy: IfNotPresent volumeMounts: - name: www-data mountPath: /usr/share/nginx/html - name: doom-client-nginx-vol mountPath: /etc/nginx/conf.d
  • 26. Kubernetes shared persistentKubernetes shared persistent volumevolume volumes: - name: www-data emptyDir: {} - name: doom-client-nginx-vol configMap: name: doom-client-nginx
  • 27. Local developmentLocal development environmentenvironment Docker Compose services: webpack dev server backend API services NGINX instance for production build testing
  • 28. UI service (webpackUI service (webpack dev server)dev server) version: '3' services: ui: build: . command: ["npm", "run", "dev", ] ports: - "8080:8080" environment: - HOST=0.0.0.0 - PORT=8080 - NODE_ENV=development - DOOM_ENGINE_SERVICE_URL=http://localhost:8081/ - DOOM_STATE_SERVICE_URL=http://localhost:8082/ volumes: - .:/app # bind volume inside container for source mount not shadow image d - /app/node_modules - /app/dist
  • 29. Backend servicesBackend services doom-engine: image: microservice-doom/doom-engine:latest environment: - DOOM_STATE_SERVICE_URL=http://doom-state:8080/ - DOOM_STATE_SERVICE_PASSWORD=enginepwd ports: - "8081:8080" doom-state: image: microservice-doom/doom-state:latest ports: - "8082:8080"
  • 30. Production build test servicesProduction build test services ui-deployment: build: . command: ["/app/bin/rewrite-config.js"] environment: - NODE_ENV=production - DIST_DIR=/app/dist - WWW_DIR=/tmp/www - DOOM_ENGINE_SERVICE_URL=http://localhost:8081/ - DOOM_STATE_SERVICE_URL=http://localhost:8082/ volumes: - .:/app # bind volume inside container for source mount not shadow image d - /app/node_modules - /app/dist # shared NGINX static files dir - www-data:/tmp/www depends_on: - nginx
  • 31. Test production build withTest production build with NGINXNGINX nginx: image: nginx:1.14 ports: - "8090:80" volumes: - www-data:/usr/share/nginx/html # shared persistent volume volumes: www-data:
  • 33. Shameless plugShameless plug https://container-solutions.com/deploying-con gurable- frontend-web-application-containers/
  • 34.
  • 35. Keep in touch!Keep in touch! Twitter: @zemanel E-mail: jose.moreira@container-solutions.com LinkedIn: https://www.linkedin.com/in/josemoreira