SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
NodeJS in Production
William Bruno
Desenvolvedor NodeJS
http://wbruno.com.br/
http://github.com/wbruno
wbrunom@gmail.com
@wbrunom
use istanbul
use jshint
relatório de cobertura dos seus testes
análise estática de código, check de sintaxe
seja rápido
Seja extremamente rápido, quanto menos tempo de NodeJS sua
aplicação tiver, mais ela irá escalar.
Assíncrono
Single Thread
V8 usa no máximo 1.6GB de RAM por processo
Consome pouca RAM e pouca CPU
use cluster
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) {
let worker = cluster.fork();
worker.on('error', _onWorkerError);
}
} else { //… }
use Objetos Literais
let AccountController = {
login: function doLogin(request, response, next) {
//..
}
};
module.exports = AccountController;
require() é síncrono, cacheado e singleton
use gzip
app.use(compression());
não use módulos desnecessários
helmet
lodash/undescore
app.disable('etag');
app.disable('x-powered-by');
outros cabeçalhos no nginx
use programação funcional
[].filter();
[].map();
[].some();
[].every();
[].find();
[].reduce();
Monads, clousures, currying,
HOF, avoid side-effects, etc
use es6
Nativa desde o NodeJS 4.0

Esqueça Babel
'use strict';
let express = require('express');
use mozilla/nunjucks
Ótimo template engine
Mantido pela Fundação Mozilla
nomeie seus middlewares
app.get('/', function getHome(request, response, next) {
response.send('Home');
});
erros num único ponto
Trate os erros num único lugar
app.use(function handleError(err, request, response, next) {
response.status(err.status || 500);
//log
if (request.xhr) {
response.json({ err: err.message });
} else {
response.render('error', {
message: err.message
});
}
});
use debug
Não deixe console.log() perdidos no código
Tudo o que vai para o std output escreve no log
escreva log
winston [splunk, graylog]
quem, quando, o quê
use newrelic
SERVER

APM

BROWSER
use a lib bluebird
Mais rápida que a implementação nativa de Promise

Possui o método .promisifyAll()
use npm scripts
{
"name": "app",
"scripts": {
"gulp": "gulp; ./scripts.sh akamai; gulp s3",
"jshint": "jshint server/*",
"karma": "./scripts.sh karma",
"nodemon": "nodemon ./server/bin/www",
"patch": "npm version patch -m "release: version %s" && git push --tags && git push",
"start": "./scripts.sh start",
"test": "./scripts.sh test"
},
use npm scripts#!/bin/bash
BROWSER=${2:-"PhantomJS"}
case "$1" in
start)
echo 'Starting...'
export DEBUG=blz:*
bower install
npm-run-all --parallel gulp-watch karma
;;
test)
echo 'Testing backend...'
gulp eslint:nodejs
export DEBUG=blz:*
./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha test/nodejs/*
;;
karma)
echo 'Testing frontend...'
gulp eslint:angular
gulp eslint:jquery
./node_modules/karma/bin/karma start --browsers $BROWSER ./test/angular/karma.conf.js
;;
akamai)
echo 'Updating akamai...'
export APPLICATION_VERSION=$(node -e "console.log(require('./package.json').version);")
mkdir -p _akamai/$APPLICATION_VERSION
cp -r dist/public/* _akamai/$APPLICATION_VERSION
chmod 400 akamai.key
scp -i akamai.key -o StrictHostKeyChecking=no -rp _akamai/$APPLICATION_VERSION user@..…upload.akamai.com:/dir/
;;
*)
echo "Usage: {start|akamai|test|karma}"
exit 1
;;
esac
use forever para prod
e nodemon para dev
use /etc/init.d/nodejs
ou /etc/init/nodejs
Unix Service ou Ubuntu upstart
https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production
https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production
#!/bin/sh
### BEGIN INIT INFO
# Provides: nodejs init script
# Required-Start: forever node module
# X-Interactive: true
# Short-Description: application initscript
# Description: Uses forever module to running the application
### END INIT INFO
NODE_ENV="{{ enviroment }}"
PORT="3002"
APP_DIR="/var/{{ application }}/dist/server"
NODE_APP="bin/www"
CONFIG_DIR="$APP_DIR/config"
LOG_DIR="/var/log/{{ application }}"
LOG_FILE="$LOG_DIR/app.log"
NODE_EXEC="forever"
###############
USAGE="Usage: $0 {start|stop|restart|status}"
start_app() {
mkdir -p "$LOG_DIR"
echo "Starting node app ..."
PORT="$PORT" NODE_ENV="$NODE_ENV" NODE_CONFIG_DIR="$CONFIG_DIR"
forever start "$APP_DIR/$NODE_APP" 1>"$LOG_FILE" 2>&1 &
}
stop_app() {
forever stop "$APP_DIR/$NODE_APP"
}
status_app() {
forever list
}
restart_app() {
forever restart "$APP_DIR/$NODE_APP"
}
case "$1" in
start)
start_app
;;
stop)
stop_app
;;
restart)
restart_app
;;
status)
status_app
;;
*)
echo $USAGE
exit 1
;;
esac
Unix service
https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production
start on filesystem and started networking
stop on shutdown
expect fork
setuid www-data
env HOME="/var/{{ application }}"
env NODE_ENV="{{ enviroment }}"
env MIN_UPTIME="5000"
env SPIN_SLEEP_TIME="2000"
chdir /var/{{ application }}/dist/server
env APP_EXEC="bin/www"
script
exec forever -a -l $HOME/forever.log --minUptime=$MIN_UPTIME --spinSleepTime=$SPIN_SLEEP_TIME start $APP_EXEC
end script
pre-stop script
exec forever stopall
end script
Ubuntu upstart
use o nginx-full
Ótimo web server
Ultra rápido
Assíncrono, não bloqueante
Super configurável
http2 (server push apenas no plus)
https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production
server {
listen 80;
server_name www.{{ domain }};
access_log /var/{{ application }}/www.{{ domain }}-access.log;
error_log /var/{{ application }}/www.{{ domain }}-error.log;
proxy_cache one;
root /var/{{ application }}/dist/public/;
error_page 400 404 414 500 502 503 504 /50x.html;
location /50x.html {
internal;
}
location /api {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://nodejs/api;
}
location ~* .(?:ico|css|html|json|js|gif|jpe?g|png|ttf|woff|woff2|svg|eot|txt)$ {
access_log off;
expires 14d;
add_header Pragma public;
add_header Cache-Control "public, mustrevalidate, proxy-revalidate";
root /var/{{ application }}/dist/public;
}
}
location / {
add_header X-Cache-Status $upstream_cache_status;
add_header Strict-Transport-Security
"max-age=1440; includeSubdomains";
expires 60s;
set $mobile ‘@desktop';
if ($http_user_agent ~* "...") {
set $mobile "@tablet";
}
if ($http_user_agent ~* "...") {
set $mobile "@smartphone";
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_ignore_headers Cache-Control;
proxy_pass http://nodejs;
proxy_cache_key "$mobile$scheme://$host$request_uri";
proxy_cache_bypass $cookie_nocache $arg_nocache;
proxy_cache_valid 1m;
proxy_cache_min_uses 1;
}
https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 60;
send_timeout 60;
client_body_timeout 60;
client_header_timeout 60;
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 32k;
types_hash_max_size 2048;
server_tokens off;
server_names_hash_bucket_size 64;
default_type application/octet-stream;
log_format elb '$http_x_forwarded_for - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
proxy_cache_path /tmp/cache keys_zone=one:10m loader_threshold=100 loader_files=100 loader_sleep=30 inactive=30m max_size=2g;
charset utf-8;
gzip on;
gzip_disable "msie6";
gzip_min_length 1;
gzip_types *;
gzip_http_version 1.1;
gzip_vary on;
gzip_comp_level 6;
gzip_proxied any;
gzip_buffers 16 8k;
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
include /etc/nginx/upstreams.d/nodejs;
}
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
Bibliografia
https://promisesaplus.com
https://blog.risingstack.com/node-js-best-practices/
https://www.sitepoint.com/10-tips-make-node-js-web-app-faster/
http://expressjs.com/en/advanced/best-practice-performance.html
https://www.packtpub.com/books/content/fine-tune-nginx-configufine-tune-
nginx-configurationfine-tune-nginx-configurationratio
https://www.nginx.com/blog/nginx-caching-guide/
https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production
Obrigado
Nodejs in Production

Weitere ähnliche Inhalte

Was ist angesagt?

Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
ConFoo
 

Was ist angesagt? (20)

All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Node ppt
Node pptNode ppt
Node ppt
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Intro to node and non blocking io
Intro to node and non blocking ioIntro to node and non blocking io
Intro to node and non blocking io
 

Andere mochten auch

Andere mochten auch (20)

Control your house with the elePHPant - PHPConf2016
Control your house with the elePHPant - PHPConf2016Control your house with the elePHPant - PHPConf2016
Control your house with the elePHPant - PHPConf2016
 
NodeMN: Building AI into your Node.js apps
NodeMN: Building AI into your Node.js appsNodeMN: Building AI into your Node.js apps
NodeMN: Building AI into your Node.js apps
 
[Js hcm] Deploying node.js with Forever.js and nginx
[Js hcm] Deploying node.js with Forever.js and nginx[Js hcm] Deploying node.js with Forever.js and nginx
[Js hcm] Deploying node.js with Forever.js and nginx
 
Building Web Apps & APIs With Node JS
Building Web Apps & APIs With Node JSBuilding Web Apps & APIs With Node JS
Building Web Apps & APIs With Node JS
 
NodeJS security - still unsafe at most speeds - v1.0
NodeJS security - still unsafe at most speeds - v1.0NodeJS security - still unsafe at most speeds - v1.0
NodeJS security - still unsafe at most speeds - v1.0
 
Testing NodeJS Security
Testing NodeJS SecurityTesting NodeJS Security
Testing NodeJS Security
 
Nicolas-Embleton - Deploying node.js with forever and nginx
Nicolas-Embleton  - Deploying node.js with forever and nginxNicolas-Embleton  - Deploying node.js with forever and nginx
Nicolas-Embleton - Deploying node.js with forever and nginx
 
Building Killer RESTful APIs with NodeJs
Building Killer RESTful APIs with NodeJsBuilding Killer RESTful APIs with NodeJs
Building Killer RESTful APIs with NodeJs
 
Come Sail Away With Me (you guys): Node.js MVC Web API's Using Sails.js
Come Sail Away With Me (you guys): Node.js MVC Web API's Using Sails.jsCome Sail Away With Me (you guys): Node.js MVC Web API's Using Sails.js
Come Sail Away With Me (you guys): Node.js MVC Web API's Using Sails.js
 
Arduino day 2015 - UFABC (PT-BR)
Arduino day 2015 - UFABC (PT-BR)Arduino day 2015 - UFABC (PT-BR)
Arduino day 2015 - UFABC (PT-BR)
 
7º Connecting Knowledge (PT-BR)
7º Connecting Knowledge (PT-BR)7º Connecting Knowledge (PT-BR)
7º Connecting Knowledge (PT-BR)
 
Web Development with Node.js
Web Development with Node.jsWeb Development with Node.js
Web Development with Node.js
 
Microservices and Seneca at RomaJS group
Microservices and Seneca at RomaJS groupMicroservices and Seneca at RomaJS group
Microservices and Seneca at RomaJS group
 
Nginx, PHP and Node.js
Nginx, PHP and Node.jsNginx, PHP and Node.js
Nginx, PHP and Node.js
 
Node Interactive : 7 years, 7 design patterns, will node continue to outshine
Node Interactive : 7 years, 7 design patterns, will node continue to outshineNode Interactive : 7 years, 7 design patterns, will node continue to outshine
Node Interactive : 7 years, 7 design patterns, will node continue to outshine
 
The Seneca Pattern at EngineYard Distill 2013 Conference
The Seneca Pattern at EngineYard Distill 2013 ConferenceThe Seneca Pattern at EngineYard Distill 2013 Conference
The Seneca Pattern at EngineYard Distill 2013 Conference
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
Writing Test Cases with PHPUnit
Writing Test Cases with PHPUnitWriting Test Cases with PHPUnit
Writing Test Cases with PHPUnit
 
NodeJS Microservices, Built it Now, Scale it Later!
NodeJS Microservices, Built it Now, Scale it Later!NodeJS Microservices, Built it Now, Scale it Later!
NodeJS Microservices, Built it Now, Scale it Later!
 
Richard rodger technical debt - web summit 2013
Richard rodger   technical debt - web summit 2013Richard rodger   technical debt - web summit 2013
Richard rodger technical debt - web summit 2013
 

Ähnlich wie Nodejs in Production

Node.js basics
Node.js basicsNode.js basics
Node.js basics
Ben Lin
 
Provisioning with Puppet
Provisioning with PuppetProvisioning with Puppet
Provisioning with Puppet
Joe Ray
 
X64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newX64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 new
Yiwei Ma
 

Ähnlich wie Nodejs in Production (20)

Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Grunt & Front-end Workflow
Grunt & Front-end WorkflowGrunt & Front-end Workflow
Grunt & Front-end Workflow
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With You
 
OSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshopOSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshop
 
How to go the extra mile on monitoring
How to go the extra mile on monitoringHow to go the extra mile on monitoring
How to go the extra mile on monitoring
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.cat
 
Provisioning with Puppet
Provisioning with PuppetProvisioning with Puppet
Provisioning with Puppet
 
Front-end tools
Front-end toolsFront-end tools
Front-end tools
 
Cooking with Chef
Cooking with ChefCooking with Chef
Cooking with Chef
 
AMS Node Meetup December presentation Phusion Passenger
AMS Node Meetup December presentation Phusion PassengerAMS Node Meetup December presentation Phusion Passenger
AMS Node Meetup December presentation Phusion Passenger
 
X64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newX64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 new
 
EC2
EC2EC2
EC2
 
Plone deployment made easy
Plone deployment made easyPlone deployment made easy
Plone deployment made easy
 
Capifony. Minsk PHP MeetUp #11
Capifony. Minsk PHP MeetUp #11Capifony. Minsk PHP MeetUp #11
Capifony. Minsk PHP MeetUp #11
 
Docker deploy
Docker deployDocker deploy
Docker deploy
 
Npm scripts
Npm scriptsNpm scripts
Npm scripts
 
Continuous Delivery: The Next Frontier
Continuous Delivery: The Next FrontierContinuous Delivery: The Next Frontier
Continuous Delivery: The Next Frontier
 
NGINX Can Do That? Test Drive Your Config File!
NGINX Can Do That? Test Drive Your Config File!NGINX Can Do That? Test Drive Your Config File!
NGINX Can Do That? Test Drive Your Config File!
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 

Mehr von William Bruno Moraes

Mehr von William Bruno Moraes (10)

blz-ecomm.pdf
blz-ecomm.pdfblz-ecomm.pdf
blz-ecomm.pdf
 
Projetando um clube fidelidade para 50 milhões de clientes
Projetando um clube fidelidade para 50 milhões de clientesProjetando um clube fidelidade para 50 milhões de clientes
Projetando um clube fidelidade para 50 milhões de clientes
 
Javascript fullstasck
Javascript fullstasckJavascript fullstasck
Javascript fullstasck
 
Functional javascript
Functional javascriptFunctional javascript
Functional javascript
 
APIs REST escaláveis
APIs REST escaláveisAPIs REST escaláveis
APIs REST escaláveis
 
I Promise You
I Promise YouI Promise You
I Promise You
 
Boas Práticas em jQuery
Boas Práticas em jQueryBoas Práticas em jQuery
Boas Práticas em jQuery
 
Repensando seu CSS - Boas práticas e performance
Repensando seu CSS - Boas práticas e performanceRepensando seu CSS - Boas práticas e performance
Repensando seu CSS - Boas práticas e performance
 
Afinal o que é a web
Afinal o que é a webAfinal o que é a web
Afinal o que é a web
 
Responsive webdesign
Responsive webdesignResponsive webdesign
Responsive webdesign
 

Kürzlich hochgeladen

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Kürzlich hochgeladen (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 

Nodejs in Production

  • 3. use istanbul use jshint relatório de cobertura dos seus testes análise estática de código, check de sintaxe
  • 4. seja rápido Seja extremamente rápido, quanto menos tempo de NodeJS sua aplicação tiver, mais ela irá escalar. Assíncrono Single Thread V8 usa no máximo 1.6GB de RAM por processo Consome pouca RAM e pouca CPU
  • 5. use cluster if (cluster.isMaster) { for (let i = 0; i < numCPUs; i++) { let worker = cluster.fork(); worker.on('error', _onWorkerError); } } else { //… }
  • 6. use Objetos Literais let AccountController = { login: function doLogin(request, response, next) { //.. } }; module.exports = AccountController; require() é síncrono, cacheado e singleton
  • 8. não use módulos desnecessários helmet lodash/undescore app.disable('etag'); app.disable('x-powered-by'); outros cabeçalhos no nginx
  • 10. use es6 Nativa desde o NodeJS 4.0
 Esqueça Babel 'use strict'; let express = require('express');
  • 11. use mozilla/nunjucks Ótimo template engine Mantido pela Fundação Mozilla
  • 12. nomeie seus middlewares app.get('/', function getHome(request, response, next) { response.send('Home'); });
  • 13. erros num único ponto Trate os erros num único lugar app.use(function handleError(err, request, response, next) { response.status(err.status || 500); //log if (request.xhr) { response.json({ err: err.message }); } else { response.render('error', { message: err.message }); } });
  • 14. use debug Não deixe console.log() perdidos no código Tudo o que vai para o std output escreve no log
  • 15. escreva log winston [splunk, graylog] quem, quando, o quê
  • 17. use a lib bluebird Mais rápida que a implementação nativa de Promise
 Possui o método .promisifyAll()
  • 18. use npm scripts { "name": "app", "scripts": { "gulp": "gulp; ./scripts.sh akamai; gulp s3", "jshint": "jshint server/*", "karma": "./scripts.sh karma", "nodemon": "nodemon ./server/bin/www", "patch": "npm version patch -m "release: version %s" && git push --tags && git push", "start": "./scripts.sh start", "test": "./scripts.sh test" },
  • 19. use npm scripts#!/bin/bash BROWSER=${2:-"PhantomJS"} case "$1" in start) echo 'Starting...' export DEBUG=blz:* bower install npm-run-all --parallel gulp-watch karma ;; test) echo 'Testing backend...' gulp eslint:nodejs export DEBUG=blz:* ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha test/nodejs/* ;; karma) echo 'Testing frontend...' gulp eslint:angular gulp eslint:jquery ./node_modules/karma/bin/karma start --browsers $BROWSER ./test/angular/karma.conf.js ;; akamai) echo 'Updating akamai...' export APPLICATION_VERSION=$(node -e "console.log(require('./package.json').version);") mkdir -p _akamai/$APPLICATION_VERSION cp -r dist/public/* _akamai/$APPLICATION_VERSION chmod 400 akamai.key scp -i akamai.key -o StrictHostKeyChecking=no -rp _akamai/$APPLICATION_VERSION user@..…upload.akamai.com:/dir/ ;; *) echo "Usage: {start|akamai|test|karma}" exit 1 ;; esac
  • 20. use forever para prod e nodemon para dev
  • 21. use /etc/init.d/nodejs ou /etc/init/nodejs Unix Service ou Ubuntu upstart https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production
  • 22. https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production #!/bin/sh ### BEGIN INIT INFO # Provides: nodejs init script # Required-Start: forever node module # X-Interactive: true # Short-Description: application initscript # Description: Uses forever module to running the application ### END INIT INFO NODE_ENV="{{ enviroment }}" PORT="3002" APP_DIR="/var/{{ application }}/dist/server" NODE_APP="bin/www" CONFIG_DIR="$APP_DIR/config" LOG_DIR="/var/log/{{ application }}" LOG_FILE="$LOG_DIR/app.log" NODE_EXEC="forever" ############### USAGE="Usage: $0 {start|stop|restart|status}" start_app() { mkdir -p "$LOG_DIR" echo "Starting node app ..." PORT="$PORT" NODE_ENV="$NODE_ENV" NODE_CONFIG_DIR="$CONFIG_DIR" forever start "$APP_DIR/$NODE_APP" 1>"$LOG_FILE" 2>&1 & } stop_app() { forever stop "$APP_DIR/$NODE_APP" } status_app() { forever list } restart_app() { forever restart "$APP_DIR/$NODE_APP" } case "$1" in start) start_app ;; stop) stop_app ;; restart) restart_app ;; status) status_app ;; *) echo $USAGE exit 1 ;; esac Unix service
  • 23. https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production start on filesystem and started networking stop on shutdown expect fork setuid www-data env HOME="/var/{{ application }}" env NODE_ENV="{{ enviroment }}" env MIN_UPTIME="5000" env SPIN_SLEEP_TIME="2000" chdir /var/{{ application }}/dist/server env APP_EXEC="bin/www" script exec forever -a -l $HOME/forever.log --minUptime=$MIN_UPTIME --spinSleepTime=$SPIN_SLEEP_TIME start $APP_EXEC end script pre-stop script exec forever stopall end script Ubuntu upstart
  • 24. use o nginx-full Ótimo web server Ultra rápido Assíncrono, não bloqueante Super configurável http2 (server push apenas no plus)
  • 25. https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production server { listen 80; server_name www.{{ domain }}; access_log /var/{{ application }}/www.{{ domain }}-access.log; error_log /var/{{ application }}/www.{{ domain }}-error.log; proxy_cache one; root /var/{{ application }}/dist/public/; error_page 400 404 414 500 502 503 504 /50x.html; location /50x.html { internal; } location /api { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_pass http://nodejs/api; } location ~* .(?:ico|css|html|json|js|gif|jpe?g|png|ttf|woff|woff2|svg|eot|txt)$ { access_log off; expires 14d; add_header Pragma public; add_header Cache-Control "public, mustrevalidate, proxy-revalidate"; root /var/{{ application }}/dist/public; } } location / { add_header X-Cache-Status $upstream_cache_status; add_header Strict-Transport-Security "max-age=1440; includeSubdomains"; expires 60s; set $mobile ‘@desktop'; if ($http_user_agent ~* "...") { set $mobile "@tablet"; } if ($http_user_agent ~* "...") { set $mobile "@smartphone"; } proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_ignore_headers Cache-Control; proxy_pass http://nodejs; proxy_cache_key "$mobile$scheme://$host$request_uri"; proxy_cache_bypass $cookie_nocache $arg_nocache; proxy_cache_valid 1m; proxy_cache_min_uses 1; }
  • 26. https://github.com/wbruno/examples/tree/gh-pages/nodejs-in-production http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 60; send_timeout 60; client_body_timeout 60; client_header_timeout 60; client_body_buffer_size 10K; client_header_buffer_size 1k; client_max_body_size 8m; large_client_header_buffers 4 32k; types_hash_max_size 2048; server_tokens off; server_names_hash_bucket_size 64; default_type application/octet-stream; log_format elb '$http_x_forwarded_for - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"'; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; proxy_cache_path /tmp/cache keys_zone=one:10m loader_threshold=100 loader_files=100 loader_sleep=30 inactive=30m max_size=2g; charset utf-8; gzip on; gzip_disable "msie6"; gzip_min_length 1; gzip_types *; gzip_http_version 1.1; gzip_vary on; gzip_comp_level 6; gzip_proxied any; gzip_buffers 16 8k; include /etc/nginx/mime.types; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; include /etc/nginx/upstreams.d/nodejs; } user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 1024; multi_accept on; use epoll; }