NGINX 101 - 19x

Transcription

NGINX 101Now withmore Docker

Core NGINX functionality includes HTTPrequest, proxy and caching services whichcan be combined into a completeapplication delivery platform. Or, as welike to think of it .

The originsNGINX development began at Rambler.ruby Igor Sysoev to solve c10k problem High concurrency Low memory use 2002 commodity hardware

High on.com/2008/12/a- ‐li3le- ‐holiday- ‐present- ‐10000- ‐reqssec- ‐with- ‐nginx- ‐2/

Low Memory 008/12/a- ‐li3le- ‐holiday- ‐present- ‐10000- ‐reqssec- ‐with- ‐nginx- ‐2/

Apache is like MicrosoftWord, it has a million optionsbut you only need six. Nginxdoes those six things, and itdoes five of them 50 timesfaster than Apache.- Chris LeaLearn more at nginx.com

Questions before you begin1. What functionality do you require? Standard modules NGINX Plus functionality Optional NGINX and third-partymodules3. How do you want to install? 2. What branch do you want totrack? Mainline (1.7) Stable (1.6) Something older?“Official” NGINX packages (nginx.org)Build from SourceFrom Operating System repositoryFrom Amazon AWS MarketplaceFrom Docker Hub Registryh3p://nginx.com/blog/nginx- ‐1- ‐6- ‐1- ‐7- ‐released/

Traditional Installation wget http://nginx.org/keys/nginx signing.key sudo apt-key add nginx signing.key# cat /etc/apt/sources.list.d/nginx.listdeb http://nginx.org/packages/mainline/ubuntu/ trusty nginxdeb-src http://nginx.org/packages/mainline/ubuntu/ trusty nginx# apt-get update# apt-cache policy nginxnginx:Installed: (none)Candidate: 1.7.0-1 trustyVersion table:1.7.0-1 trusty 0500 http://nginx.org/packages/mainline/ubuntu/ trusty/nginx amd64 Packages1.4.6-1ubuntu3 0500 http://us.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packagesh3p://nginx.org/en/linux packages.html#mainline

Verify it’s working# /etc/init.d/nginx status* nginx is running# /usr/sbin/nginx –vnginx version: nginx/1.7.0

The basics of the install

Where are the things NGINX executable is at /usr/sbin/nginx Configuration files at /etc/nginx Log files at /var/log/nginx

NGINX processes One master process and many workerprocesses The master process evaluates theconfiguration file and manages the workerprocesses Worker processes handle actual requests[root@localhost ]# ps -ef grep nginxroot19911 0 08:06 ?00:00:00 nginx: masterprocess /usr/sbin/nginx -c /etc/nginx/nginx.confnginx2974 1991 0 08:22 ?00:00:00 nginx: workerprocessnginx2975 1991 0 08:22 ?00:00:00 nginx: workerprocess

Basic NGINX commands To start NGINX, simply run the executablefile at /usr/sbin/nginx The executable can be run with a “-s”parameter followed by a signal.Reloadconfigura.onnginx –s �nishprocessingrequestsnginx –s quitFastshutdownnginx –s stop

The NGINX configuration file The configuration file determines howNGINX and its modules behave The main file is named nginx.conf and islocated in /etc/nginx The main configuration file may includereferences to additional configuration files Configuration consists of– Directives– Blocks– Contexts

Configuration directives

DirectivesA Directive is a configuration statement that controlsthe behaviour of NGINX modules Consists of the directive name, followed byparameters and ends in a semicolon Two types of directives– Simple directive– Block directive

Block DirectivesA Block Directive is a directive that contains multipleconfiguration instructions The configurations instructions inside ablock directive are surrounded by braces(i.e { } )

Context example Example of aServer context,which has twolocation blocks The servercontext herecan also bereferred to as aserver block

Specify the Server BlockThe Server block defines the configuration for a virtualserver Goes inside the HTTP context Can contain a listen directive, server namedirective and root directive Can specify many server blocks Equivalent to VirtualHost in Apache

Specify the Server BlockThe Server block defines the configuration for a virtualserver NGINX will choose which server to processa request based on the server name andthe listen portDefine a virtual server that listens for requests on port 80http {server {listen 80;}}

Location Block The location block defines the configuration thatwill apply based on a matching request URI Placed inside a server block Server block can contain many location blocks Can contain a Root directive, which willoverride the Root directive of the server Can be nested inside a location block Two types of location blocksPrefix location Regex location

Example Server and Location Root directive sets the root directory for arequest. A request to localhost:8080 will return the index.html file in /home/nginx/public htmlserver {listen 8080;root /home/nginx/public html;location /application1 {}location /images/ {root /data;}}

The Include directive The include directive allows you toinclude additional configuration files Syntax: include path to file ; Best Practices:– For each server, create a separateconfiguration file in /etc/nginx/conf.d– nginx.conf includes all files in the conf.dfolder ending in .conf by default

Defining server names Use the server name directive in the servercontext to define the names for your serverserver {server name mycompany.com *.mycompany.com;}

Simple Proxy Scenario Server one listening for requests on port80 and serves content from /home/nginx/public html Server two listens on port 8080 andserves content from /data/proxy Requests for localhost are proxied overto the server on port 8080

Simple Proxy Scenario

Logging The error log directive can be used to configurethe logging settings Syntax:error log file log level ; Can be used in the main, server, http andlocation contexts The Log level specifies how detailed the logoutput will beExampleerror loglogs/error.log info;

Logging best practices Should keep a separate error log file foreach server Helps to reduce size of each log file andmakes troubleshooting easierserver {server name server1.com;root /data/server1.com;error log logs/server1.error.log}server {server name server2.comroot /data/server2.com;error log logs/server2.error.log}info;info;

Proxying to the upstream block

Specifying server priorities By default, all servers defined in theupstream block are treated with equalpriority Use the weight parameter to indicate ahigher or lower weighting for a particularserverupstream myServers {server backend.server1 weight 5server backend.server2 weight 3server backend.server3 weight 2}

Reverse proxy and caching It’s common to use NGINX in front ofanother web or application server NGINX can handle serving all the staticcontent, while requests for dynamiccontent such as php are proxied to theapplication server Static content can then be cached toimprove performance

Defining the cache pathhttp {proxy cache path /var/cache/nginx levels 1:2keys zone server-cache:8m max size 1000minactive 600m;proxy temp path /tmp/nginx; proxy cache path directive to set where tostore cached content proxy temp path directive tells NGINX where tostore temporary data which is used to build thecache Both directives must be placed in HTTP context

Defining the cache path proxy cache path parameters– keys zone parameter specifies the nameand size of the cache– max size parameter specifies the maximumsize of the cache– Inactive parameter specifies how longcached data is kept for if not accessed

Configuring the proxy cache proxy cache key directive specifies to use thehostname/subdomain/domain and request URI as thekey proxy cache directive defines the shared memoryzone used for caching.– Name specified must match the name of the cachedefined in the proxy cache path directiveLocation / {proxy pass http://application.com:8080;proxy cache key “ scheme host request uri”;proxy cache server-cache;proxy chache valid 1m;proxy cache valid 404 1m;]

Passing headers Use proxy set header directive to redefine therequest header fields that are passed to theproxied server Use this to pass on the hostname and IP addressof the request machine Without setting the headers, the server youproxy to will simply see your reverse proxyserver’s host and IPproxy set headerproxy set headerproxy set headerHost host;X-Real-IP remote addr;X-Forwarded-For proxy add x forwarded for;

Configuring a HTTPS server Enable SSL by specifying the SSLparameter on the listen directive Specify the path of your SSL servercertificate and private keyserver {listen443 ssl;server name training.secure.com;error loglogs/secure.error.log;ssl certificate /etc/nginx/certs/nginxtraining.crtssl certificate key /etc/nginx/certs/nginxtraining.key]

SSL session cache SSL sessions can be stored in a cache andreused in order to avoid having to perform a“handshake” as part of subsequentconnections Reduces the amount of CPU intensiveoperations on the server The session cache can be shared betweenworkers Cache will timeout after 5 minutes bydefault, but this can be configured with thessl session timeout directive

Session cache example Syntaxssl session cache shared: name :size; Size is specified in bytes or megabytes 1 MB can store around 4000 sessions Can specified in the http or server contextExamplehttp {ssl session cache shared:ssl:10m;ssl session timeout 10m;server {listen 443 ssl;.

Now withmore Docker

registry.hub.docker.com

DockerfileFROM debian:wheezyMAINTAINER NGINX Docker Maintainers "docker-maint@nginx.com"RUN apt-key adv --keyserver pgp.mit.edu 2RUN echo "deb http://nginx.org/packages/mainline/debian/ wheezy nginx" /etc/apt/sources.listENV NGINX VERSION 1.7.10-1 wheezyRUN apt-get update && \apt-get install -y ca-certificates nginx {NGINX VERSION} && \rm -rf /var/lib/apt/lists/*# forward request and error logs to docker log collectorRUN ln -sf /dev/stdout /var/log/nginx/access.logRUN ln -sf /dev/stderr /var/log/nginx/error.logVOLUME ["/var/cache/nginx"]EXPOSE 80 443CMD ["nginx", "-g", "daemon off;"]

Run our Docker container docker run -P –d 43f47a3a38029a56b14# docker psCONTAINER IDSTATUSff635ea2653cUp 11 ginx -g 'daemon of16 seconds ago0.0.0.0:49153- 443/tcp, 0.0.0.0:49154- 80/tcpnginx-testhAps://registry.hub.docker.com/ /nginx/

Exploring our Docker container docker@52.10.213.150 : docker run-it nginx /bin/bashroot@74d2a7e93244:/# more /etc/nginx/nginx.confuser nginx;worker processeserror logpid1;/var/log/nginx/error.log warn;/var/run/nginx.pid;events {worker connections}http {includedefault typelog format m;main' remote addr - remote user [ time local] " request" '' status body bytes sent " http referer" ''" http user agent" " http x forwarded for"’;

Extending base images in your E13x

Your NGINX DockerfileFROM nginxRUN rm /etc/nginx/conf.d/default.confRUN rm /etc/nginx/conf.d/example ssl.confCOPY static-html-directory /usr/share/nginx/htmlCOPY nginx.conf /etc/nginx/nginx.conf Fancier options i.e. more repeatable and scalable– Defining VOLUMEs– Using helper containers– Linking containersh3p://nginx.com/blog/deploying- ‐nginx- ‐nginx- ‐plus- ‐docker/

@sarahnovotnyChief Evangelist, NGINXProgram Chair, OSCONThanks for your time!http://sarah.is/ExcitedAboutMicroservices

Core NGINX functionality includes HTTP request, proxy and caching services which can be combined into a complete application delivery platform. Or, as we like to think of it . The origins NGINX development began at Rambler.ru by Igor Sysoev to solve c10k problem