来自Nginx公司的工程师介绍什么Ngnix,怎么安装nginx以及nginx+,主要的配置文件,命令和文件夹,也谈到了基本配置和高级配置选项,包括大量的配置选项和相关原理介绍,可以作为网站运维人员入门的参考,最后也谈到了日志和监控文件管理。

献良发布于2018/10/02 13:46

注脚

1.NGINX: Basics and Best Practices

2.Who are we? Faisal Memon Anthony Leverington Product Marketing Manager, NGINX Country Manager, ANZ, NGINX Formerly: Formerly: • Sr. Technical Marketing Engineer, Riverbed • Account Manager, AWS • Technical Marketing Engineer, Cisco • Cloud Sales Specialist, Optus • Software Engineer, Cisco • Technical Pre-Sales, VMWare

3.Agenda • Introducing NGINX • Installing NGINX and NGINX Plus • Key files, commands, and directories • Basic configurations • Advanced configurations • Logging and monitoring • Summary

4.“I wanted people to use it, so I made it open source.” - Igor Sysoev, NGINX creator and founder

5.336 million Total sites running on NGINX Source: Netcraft June 2018 Web Server Survey

6. 64% Busiest 10,000 run on NGINX Source: w3techs, June 2018

7.Our Customers

8.What is NGINX? Web Server Serve content from disk HTTP traffic Internet Load Balancer Reverse Proxy Caching, SSL termination… FastCGI, uWSGI, gRPC… NGINX Open Source NGINX Plus - Basic load balancer - Rate limiting + Advanced load balancer + JWT Authentication - Content Cache - Basic authentication + Health checks + OpenID Connect SSO - Web Server - 7 metrics + Session persistence + NGINX Plus API - Reverse Proxy + Least time alg + Dynamic modules - SSL termination + Cache purging + 90+ metrics + High Availability

9.About NGINX, Inc. • Founded in 2011, NGINX Plus first released in • Offices in SF, London, Cork, Singapore, 2013 Sydney, and Moscow • Series C funding of $43 million from Goldman • 1,500+ commercial customers Sachs and NEA • 200+ employees

10.Agenda • Introducing NGINX • Installing NGINX and NGINX Plus • Key files, commands, and directories • Basic configurations • Advanced configurations • Logging and monitoring • Summary

11.NGINX Installation Options • Official NGINX repo - Mainline (recommended) -- Actively developed; new minor releases made every 4-6 weeks with new features and enhancements. - Stable -- Updated only when critical issues or security vulnerabilities need to be fixed. • OS vendor and other 3rd party repos - Not as frequently updated; Debian Stretch has NGINX 1.10.3 - Typically built off NGINX Stable branch

12.NGINX Installation: Debian/Ubuntu Create /etc/apt/sources.list.d/nginx.list with the following contents: deb http://nginx.org/packages/mainline/OS/ CODENAME nginx deb-src http://nginx.org/packages/mainline/OS/ CODENAME nginx • OS – ubuntu or debian depending on your distro • CODENAME: - jessie or stretch for debian - trusty, xenial, artful, or bionic for ubuntu $ wget http://nginx.org/keys/nginx_signing.key $ apt-key add nginx_signing.key $ apt-get update $ apt-get install –y nginx $ /etc/init.d/nginx start

13.NGINX Installation: CentOS/Red Hat Create /etc/yum.repos.d/nginx.repo with the following contents: [nginx] name=nginx repo baseurl=http://nginx.org/packages/mainline/OS/OSRELEASE/$basearch/ gpgcheck=0 enabled=1 • OS -- rhel or centos depending on your distro • OSRELEASE -- 6 or 7 for 6.x or 7.x versions, respectively $ yum –y install nginx $ systemctl enable nginx $ systemctl start nginx $ firewall-cmd --permanent --zone=public --add-port=80/tcp $ firewall-cmd --reload

14.NGINX Plus Installation • Visit cs.nginx.com/repo_setup • Select OS from drop down list • Instructions similar to OSS installation • Mostly just using a different repo and installing client certificate

15.Verifying Installation $ nginx -v nginx version: nginx/1.15.0 $ ps -ef | grep nginx root 1088 1 0 19:59 ? 00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf nginx 1092 1088 0 19:59 ? 00:00:00 nginx: worker process

16.Verifying Installation

17.NGINX Installation Misc • For more installation details: http://nginx.org/en/linux_packages.html - List of all supported distros and CPUs - Suse Linux installation instructions • For NGINX Plus, see: https://cs.nginx.com/repo_setup - List of all supported distros and CPUs, including FreeBSD

18.Agenda • Introducing NGINX • Installing NGINX and NGINX Plus • Key files, commands, and directories • Basic configurations • Advanced configurations • Logging and monitoring • Summary

19.Key NGINX Files and Directories /etc/nginx/ /etc/nginx/conf.d/ nginx.conf virtualserver1.conf -------------------------- Global settings server { -------------------------- server listen{ <parameters>; Listen for (tunings, logs, etc) server { <parameters>; listen requests listen <parameters>; http { location <url> { ---------------------- HTTP block location <url> { Rules to handle ---------------- location <url> { include conf.d/*.conf; ---------------- each request } ---------------- } } } } } } upstream { upstream { ------------------- Optional: proxy upstream { ------------------- to upstreams } ------------------- } /var/log/nginx/ } error.log Important operational messages access.log Record of each request (configurable)

20.Key NGINX Commands • nginx –h Display NGINX help menu • nginx –t Check if NGINX configuration is ok • nginx –s reload Check config is ok and gracefully reload NGINX processes • nginx –V Similar to –v, but with more detailed information • nginx –T Dump full NGINX configuration

21.Agenda • Introducing NGINX • Installing NGINX and NGINX Plus • Key files, commands, and directories • Basic configurations • Advanced configurations • Logging and monitoring • Summary

22.Simple Virtual Server server { • server defines the context for a listen 80 default_server; virtual server server_name www.example.com; • listen specifies IP/port NGINX return 200; should listen on. No IP means bind } to all IPs on system • server_name specifies hostname of virtual server • return tells NGINX to respond directly to the request.

23.Basic Web Server Configuration server { • root specifies directory where files are stored listen 80 default_server; server_name www.example.com; • alias specifies a replacement for the specified location location /i/ { root /usr/share/nginx/html; • index defines files that will be used as an index # alias /usr/share/nginx/html; index index.html index.htm; } } • index: www.example.com -> /usr/share/nginx/html/index.html • root: www.example.com/i/file.txt -> /usr/share/nginx/html/i/file.txt • alias: www.example.com/i/file.txt -> /usr/share/nginx/html/file.txt

24.Basic Load Balancing Configuration upstream my_upstream { • upstream defines the load balancing pool server server1.example.com; server server2.example.com; • Default load balancing algorithm is round robin. least_time; Others available: } • least_conn selects server with least server { amount of active connections location / { • least_time factors in connection count proxy_set_header Host $host; and server response time. Available in NGINX Plus only. proxy_pass http://my_upstream; } • proxy_pass links virtual server to upstream } • By default NGINX rewrites Host header to name and port of proxied server. proxy_set_header overrides and passes through original client Host header.

25.Basic Reverse Proxy Configuration server { • Requires PHP FPM: location ~ ^(.+\.php)(.*)$ { apt-get install –y php7.0-fpm fastcgi_split_path_info ^(.+\.php)(.*)$; • Can also use PHP 5 # fastcgi_pass 127.0.0.1:9000; fastcgi_pass unix:/var/run/php7.0-fpm.sock; • Similar directives available for uWSGI and SCGI. fastcgi_index index.php; • Additional PHP FPM configuration may include fastcgi_params; be required } }

26.Basic Caching Configuration proxy_cache_path /path/to/cache levels=1:2 • proxy_cache_path defines the keys_zone=my_cache:10m max_size=10g parameters of the cache. inactive=60m use_temp_path=off; • keys_zone defines the size of server { memory to store cache keys in. A location / { 1 MB zone can store data for proxy_cache my_cache; about 8,000 keys. proxy_set_header Host $host; proxy_pass http://my_upstream; • max_size sets upper limit of } cache size. Optional. } • inactive defines how long an object can stay in cache without being accessed. Default is 10 m. • proxy_cache enables caching for the context it is in

27.Basic SSL Configuration server { • Force all traffic to SSL is good for listen 80 default_server; security and SEO server_name www.example.com; return 301 https://$server_name$request_uri; • Use Let’s Encrypt to get free SSL } certificates, see: server { nginx.com/blog/using-free- listen 443 ssl default_server; ssltls-certificates-from- server_name www.example.com; lets-encrypt-with-nginx ssl_certificate cert.crt; ssl_certificate_key cert.key; location / { root /usr/share/nginx/html; index index.html index.htm; } }

28.Basic HTTP/2 Configuration server { • HTTP/2 improves performance with little listen 443 ssl http2 default_server; to no backend changes server_name www.example.com; • Add http2 parameter to listen ssl_certificate cert.crt; directive of existing SSL-enabled virtual ssl_certificate_key cert.key; server. HTTP/2 is only supported with } SSL in all browsers. • NGINX only does HTTP/2 client side, server side is still HTTP/1.1. gRPC is a special case. • Note: HTTP/2 requires OpenSSL 1.0.2 or later to work properly

29.Multiplexing Multiple Sites on One IP server { • NGINX can multiplex a single listen 80 default_server; server_name www.example.com; IP/port using the Host: header. # ... } • default_server defines the server { virtual server to use if Host header listen 80; server_name www.example2.com; is empty. It is best practice to have # ... a default_server. } server { listen 80; server_name www.example3.com; # ... }

30.Layer 7 Request Routing server { • location blocks are used to do # ... Layer 7 routing based on URL location /service1 { proxy_pass http://upstream1; • Regex matching can also be used } in location blocks location /service2 { proxy_pass http://upstream2; } location /service3 { proxy_pass http://upstream3; } }

31.Agenda • Introducing NGINX • Installing NGINX and NGINX Plus • Key files, commands, and directories • Basic configurations • Advanced configurations • Logging and monitoring • Summary

32.Modifications to main nginx.conf user nginx; • Set in main nginx.conf file worker_processes auto; • Default value for worker_processes varies on # ... system and installation source http { • auto means to create one worker process per # ... core. This is recommended for most deployments. keepalive_timeout 300s; • keepalive_timeout controls how long to keep keepalive_requests 100000; idle connections to clients open. Default: 75s } • keeplive_requests Max requests on a single client connection before its closed • keepalive_* can also be set per virtual server

33.HTTP/1.1 Keepalive to Upstreams upstream my_upstream { • keepalive enables TCP connection server server1.example.com; cache keepalive 32; } • By default NGINX uses HTTP/1.0 with server { Connection: Close location / { proxy_set_header Host $host; • proxy_http_version upgrades proxy_http_version 1.1; connection to HTTP/1.1 proxy_set_header Connection ""; • proxy_set_header enables keepalive by proxy_pass http://my_upstream; } clearing Connection: Close HTTP } header

34.SSL Session Caching server { • Improves SSL/TLS performance listen 443 ssl default_server; server_name www.example.com; • 1 MB session cache can store ssl_certificate cert.crt; about 4,000 sessions ssl_certificate_key cert.key; ssl_session_cache shared:SSL:10m; • Cache shared across all NGINX ssl_session_timeout 10m; workers }

35.Advanced Caching Configuration • proxy_cache_lock instructs NGINX proxy_cache_path /path/to/cache levels=1:2 to only send one request to the keys_zone=my_cache:10m max_size=10g upstream when there are multiple inactive=60m use_temp_path=off; cache misses for the same file. server { • proxy_cache_revalidate instructs location / { NGINX to use If-Modified-Since proxy_cache my_cache; when refreshing cache. proxy_cache_lock on; proxy_cache_revalidate on; • proxy_cache_use_stale instructs proxy_cache_use_stale error timeout updating NGINX to serve stale content instead http_500 http_502 http_503 http_504; of an error. proxy_cache_background_update on; • proxy_cache_background_update proxy_set_header Host $host; instructs NGINX to do all cache updates in the background. Combined proxy_pass http://my_upstream; with proxy_cache_use_stale } updating, stale content will be } served.

36.gRPC Proxying with SSL Termination • Configure SSL and HTTP/2 as usual server { listen 443 ssl http2; • Go sample application needs to modified to point to NGINX IP ssl_certificate server.crt; Address and port. ssl_certificate_key server.key; location / { grpc_pass grpc://localhost:50051; } }

37.Active Health Checks upstream my_upstream { zone my_upstream 64k; • Polls /test.php every 5 seconds server server1.example.com slow_start=30s; } • If response is not 200, server marked server { as failed # ... location /health { internal; • If response body does not contain health_check interval=5s uri=/test.php “ServerN is alive”, server marked as match=statusok; failed d proxy_set_header HOST www.example.com; proxy_pass http://my_upstream; • Recovered/new servers will slowly } ramp up traffic over 30 seconds match statusok { # Used for /test.php health check • Exclusive to NGINX Plus status 200; header Content-Type = text/html; body ~ "Server[0-9]+ is alive"; }

38.Sticky Cookie Session Persistence upstream my_upstream { • NGINX will insert a cookie using the specified server server1.example.com; name server server2.example.com; • expires defines how long the cookie is valid sticky cookie name expires=1h for. The default is for the cookie to expire at the domain=.example.com path=/; end of the browser session. } • domain specifies the domain the cookie is valid for. If not specified, domain field of cookie is left blank • path specifies the path the cookie is set for. If not specified, path field of cookie is left blank • Exclusive to NGINX Plus

39.Agenda • Introducing NGINX • Installing NGINX and NGINX Plus • Key files, commands, and directories • Basic configurations • Advanced configurations • Logging and monitoring • Summary

40.NGINX Stub Status Module server { • Provides aggregated NGINX location /basic_status { statistics stub_status; } • Access should be locked down } so its not publically visible $ curl http://www.example.com/basic_status Active connections: 1 server accepts handled requests 7 7 7 Reading: 0 Writing: 1 Waiting: 0

41.NGINX Plus Extended Status server { • Provides detailed NGINX Plus listen 8080; statistics location /api { • Over 40+ additional metrics api write=on; • JSON data output # Limit access to the API allow 10.0.0.0/8; • Monitoring GUI also available, deny all; see demo.nginx.com } location = /dashboard.html { • Exclusive to NGINX Plus root /usr/share/nginx/html; }

42.NGINX Access Logs 192.168.179.1 - - [15/May/2017:16:36:25 -0700] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" "-" 192.168.179.1 - - [15/May/2017:16:36:26 -0700] "GET /favicon.ico HTTP/1.1" 404 571 "http://fmemon-redhat.local/" “Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" "-" 192.168.179.1 - - [15/May/2017:16:36:31 -0700] "GET /basic_status HTTP/1.1" 200 100 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" "-" • Enabled by default, can be shut off by adding “access_log off” to improve performance • By default lists client IP, date, request , referrer, user agent, etc. Can add additional NGINX variables, see nginx.org/en/docs/varindex.html • Log format configurable with the log_format directive

43.Summary • It is recommended to use the NGINX mainline branch for most deployments • All configuration should go into separate files in /etc/nginx/conf.d/*.conf • Forcing all traffic to SSL improves security and improves search rankings • Keepalive connections improve performance by reusing TCP connections • SSL session caching and HTTP/2 improve SSL performance • NGINX status module and logging capability provide visibility Try NGINX Plus for free at nginx.com/free-trial-request

44.

45. Q&A Try NGINX Plus free for 30 days: nginx.com/free-trial-request

user picture
  • 献良
  • 非著名互联网公司工程师

相关Slides