SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Downloaden Sie, um offline zu lesen
JAMES FULLER
                                   02/13/2013




Simply Scale
w/ Nginx, Memcached, PHP-FPM and APC
In this talk...
● my experiences working in a high-traffic
  environment

● intro to nginx for apache users

● running php with php-fpm

● memcached & caching tips

● identifying bottlenecks / open discussion
The Early Years



Cheap Shared Hosting
Into the fire
A Simple Scaling
Architecture
  NGINX   PHP-FPM

                    MEMCACHED
          PHP-FPM


          PHP-FPM
                    MYSQL MASTER

          PHP-FPM

                    MYSQL SLAVE
Apache
Awesome when you need to assault your server
The classic setup - prefork
MPM w/ mod_php
● prefork is default mode prior to v2.4

● forks (creates) new process per web
  resource requested

● runs php via a module (mod_php)
Apache prefork
performance killers
● Loads all modules for each forked process

● Keepalive timeout

● AllowOverride (.htaccess)
Apache 2.4
● Event MPM is now the default MPM in
  Apache 2.4

● Event MPM designed to solve the keepalive
  problem

● Can talk to PHP-FPM via mod_proxy_fcgi

● Needs thread safe php
Many reasons to keep
Apache
● apache modules

● very mature software

● can tune for good results

● plays nice with nginx!
NGINX
Russian for Fast
What is NGINX?
● HTTP Server

● Reverse Proxy

● IMAP/POP3 proxy server

● Open Source
Who is using nginx?
Nginx performance
advantages
● event based connection handling

● low/predictable memory consumption

● works well in low resource environments
  (VPS)

● can handle tens of thousands of concurrent
  requests*
Nginx as a frontend

● serve static files

● frontend for apache for php

● no apache, via PHP-FPM

● serve content directly from memcached
Nginx Configuration
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections   1024;
}

http {
     server {
          location / {
               #do something
          }
     }
}
a series of blocks
http {
    access_log /var/log/nginx/access.log   main;
    include /etc/nginx/conf.d/*.conf;
    gzip on;

    server {
        server_name myserver.com www.myserver.com
        listen 80;
        location / {

        }
    }
}
server blocks
server {
  listen 80 default_server;
  server_name star.yourdomain.com *.yourdomain.com;

    root /PATH/TO/WEBROOT;

    error_page 404 errors/404.html;
    access_log logs/star.yourdomain.com.access.log;

    index index.php index.html index.htm;

}
location blocks
# static file 404's not logged + expires header set to maxage
location ~* .(jpg|jpeg|gif|css|png|js|ico|html)$ {
  access_log off;
  expires max;
}

# deny htaccess
location ~ /.ht {
  deny all;
}
PHP-FPM
it's like mod_php without Apache
PHP-FPM are you
listening?
● included with php as of 5.3.3

● runs as a daemon
  ○ listens for requests via socket or port
     (FastCGI)

● Decouple web server from executing php
  code
Talking to php-fpm
# pass the PHP scripts to FastCGI server
# listening on 127.0.0.1:9000

location ~ .php$ {
  root           html;
  fastcgi_pass   127.0.0.1:9000;
  #fastcgi_pass unix:/tmp/php.socket
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  include        fastcgi_params;
}
Nginx for load balancing
● round robin

● least connections

● ip segmenting

● sticky backends
upstream server
upstream   backend {
  server   backend1.example.com weight=5;
  server   backend2.example.com:8080;
  server   unix:/tmp/backend3;
}

server {
  location / {
    proxy_pass   http://backend;
  }
}
apache frontend
upstream backend {
    server 192.168.1.2;
    server 192.168.1.3;
    server 192.168.1.4;
    #etc
}

location ~ .php$ {
    proxy_pass http://backend;
    proxy_set_header X-Real-IP $remote_addr;
}
Nginx Modules
Core             Log
Access           Map                        OPTIONAL
                                 Addition        Secure Link
Auth Basic       Memcached
Auto Index                       Degradation     SSL
                 Proxy
Browser                          Embedded Perl   Stub Status
                 Referer
Charset                          FLV             Substitution
                 Rewrite
Empty GIF                        GeoIP           WebDAV
                 SCGI
FastCGI                          Google
                 Split Clients                   XSLT
Geo                              Perftools
Gzip             SSI             Gzip
Headers          Upstream        Precompression
Index            User ID         Image Filter
Limit Requests   uWSGI           MP4
Limit Zone       X-Accel         Random Index
Limit Conn
                                 Real IP
Caching in PHP
Cache is king
What is Memcached?


● invented by Brad Fitzpatrick to solve
  livejournal performance problems

● distributed key value store

● super fast
Set up Memcached
instances


● small sites can use as little as 25MB

● best results and reliability in a cluster
Talking to Memcached with
PHP
● naming disaster

● php has two memcached extensions
  ○ memcache
  ○ memcached - better support for advanced
    features
  ○ wtf?

● memcache(d) php extension only on nix
  platforms (no windows)
Connecting to Memcached
<?php
$cache = new Memcache;
$cache
  ->addServer('192.168.1.2',   11211, ..[OPTIONS]..);
$cache
  ->addServer('192.168.1.3',   11211, ..[OPTIONS]..);
$cache
  ->addServer('192.168.1.4',   11211, ..[OPTIONS]..);
$cache
  ->addServer('192.168.1.5',   11211, ..[OPTIONS]..);
Simple Cache strategy
<?php
$key = 'mystash';
$data = $cache->get($key);

if ($data === false) {
  $data = 'fill up the data';
  $cache->set($key, $data, ..[OPTIONS]..);
}
Be smart about caching

● cache expensive things (network, db)

● stale content can be much worse than slow
  content

● have a plan to expire cache entries
APC
● Opcode cache

● Stores ready-to-run machine code

● will eventually be replaced by zend optimizer
  (php 5.5)

● has data caching api
Bottlenecks &
 Benchmarking



Try to identify bottlenecks
Find out what is slow
● web server

● database

● bandwidth / infrastructure

● php code
Avoid the file system
● does not scale well

● expensive to make fast

● cloud hosting and multi-server
  implementations more complicated
Database

● often the culprit

● choose the right technologies

● don't skimp on hardware
Other people's benchmarks
● Monitoring and testing is key

● avoid magical thinking:
   ○   "Magical thinking is thinking that one's thoughts by themselves can
       bring about effects in the world or that thinking something corresponds
       with doing it"

● use tools like newrelic with actual users
It's all about the end user

● avoid blocking javascript

● be aware of static assets

● use expires headers correctly
Seriously, try New Relic
● FREE basic account, with PRO TRIAL

● runs as a deamon + php extension

● allows deep inspection of web transactions

● need ability to install package on server
Homework
Dig one level deeper
● We work in abstractions

● Understand the systems that deliver your
  code to the browser

● Identify the problems before implementing
  the solutions
Resources
● nginx wiki - http://wiki.nginx.org/
● php-fpm - http://php.net/manual/en/install.fpm.php
● memcached - http://memcached.org/
● memcache extensions
  ○ memcache - http://php.net/manual/en/book.
     memcache.php
  ○ memcache(d) - http://php.net/manual/en/book.
     memcached.php
● apc - http://php.net/manual/en/book.apc.php
● newrelic - http://newrelic.com/
Questions?
   James Fuller
   @j_blotus

   http://www.jblotus.com

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Codeception: introduction to php testing (v2 - Aberdeen php)
Codeception: introduction to php testing (v2 - Aberdeen php)Codeception: introduction to php testing (v2 - Aberdeen php)
Codeception: introduction to php testing (v2 - Aberdeen php)
 
PHP Quality Assurance Workshop PHPBenelux
PHP Quality Assurance Workshop PHPBeneluxPHP Quality Assurance Workshop PHPBenelux
PHP Quality Assurance Workshop PHPBenelux
 
PHP 5.6 New and Deprecated Features
PHP 5.6  New and Deprecated FeaturesPHP 5.6  New and Deprecated Features
PHP 5.6 New and Deprecated Features
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 
Learning Puppet Chapter 1
Learning Puppet Chapter 1Learning Puppet Chapter 1
Learning Puppet Chapter 1
 
Automation testing with Drupal 8
Automation testing with Drupal 8Automation testing with Drupal 8
Automation testing with Drupal 8
 
30 Minutes To CPAN
30 Minutes To CPAN30 Minutes To CPAN
30 Minutes To CPAN
 
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
 
Maven 3.0 at Øredev
Maven 3.0 at ØredevMaven 3.0 at Øredev
Maven 3.0 at Øredev
 
Top 50 Interview Questions and Answers in CakePHP
Top 50 Interview Questions and Answers in CakePHPTop 50 Interview Questions and Answers in CakePHP
Top 50 Interview Questions and Answers in CakePHP
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flask
 
Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!
 
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
 
Debugging PHP With Xdebug
Debugging PHP With XdebugDebugging PHP With Xdebug
Debugging PHP With Xdebug
 
Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016
 
Northeast PHP - High Performance PHP
Northeast PHP - High Performance PHPNortheast PHP - High Performance PHP
Northeast PHP - High Performance PHP
 
Reliable acceptance testing
Reliable acceptance testingReliable acceptance testing
Reliable acceptance testing
 
Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
 
Continuous Quality Assurance
Continuous Quality AssuranceContinuous Quality Assurance
Continuous Quality Assurance
 
Getting started with PHPUnit
Getting started with PHPUnitGetting started with PHPUnit
Getting started with PHPUnit
 

Andere mochten auch

Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaNginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with Lua
Tony Fabeen
 

Andere mochten auch (20)

Remove web calls and scale your site like crazy !
Remove web calls and scale your site like crazy !Remove web calls and scale your site like crazy !
Remove web calls and scale your site like crazy !
 
Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012
 
Webpage Caches - the big picture (WordPress too)
Webpage Caches - the big picture (WordPress too)Webpage Caches - the big picture (WordPress too)
Webpage Caches - the big picture (WordPress too)
 
Accelerating Nginx Web Server Performance
Accelerating Nginx Web Server PerformanceAccelerating Nginx Web Server Performance
Accelerating Nginx Web Server Performance
 
Web Performance, Scalability, and Testing Techniques - Boston PHP Meetup
Web Performance, Scalability, and Testing Techniques - Boston PHP MeetupWeb Performance, Scalability, and Testing Techniques - Boston PHP Meetup
Web Performance, Scalability, and Testing Techniques - Boston PHP Meetup
 
Running PHP on Nginx / PHP wgtn
Running PHP on Nginx / PHP wgtnRunning PHP on Nginx / PHP wgtn
Running PHP on Nginx / PHP wgtn
 
5 critical-optimizations.v2
5 critical-optimizations.v25 critical-optimizations.v2
5 critical-optimizations.v2
 
High Performance Php My Sql Scaling Techniques
High Performance Php My Sql Scaling TechniquesHigh Performance Php My Sql Scaling Techniques
High Performance Php My Sql Scaling Techniques
 
Maximizing PHP Performance with NGINX
Maximizing PHP Performance with NGINXMaximizing PHP Performance with NGINX
Maximizing PHP Performance with NGINX
 
Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaNginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with Lua
 
Running php on nginx
Running php on nginxRunning php on nginx
Running php on nginx
 
mod_php vs. FastCGI 原理与比较
mod_php vs. FastCGI 原理与比较mod_php vs. FastCGI 原理与比较
mod_php vs. FastCGI 原理与比较
 
Word press on conoha このべん #3
Word press on conoha このべん #3Word press on conoha このべん #3
Word press on conoha このべん #3
 
From LAMP to LNNP
From LAMP to LNNPFrom LAMP to LNNP
From LAMP to LNNP
 
Nginx + PHP
Nginx + PHPNginx + PHP
Nginx + PHP
 
Supercharging your PHP pages with mod_lsapi in CloudLinux OS
Supercharging your PHP pages with mod_lsapi in CloudLinux OSSupercharging your PHP pages with mod_lsapi in CloudLinux OS
Supercharging your PHP pages with mod_lsapi in CloudLinux OS
 
High performance PHP: Scaling and getting the most out of your infrastructure
High performance PHP: Scaling and getting the most out of your infrastructureHigh performance PHP: Scaling and getting the most out of your infrastructure
High performance PHP: Scaling and getting the most out of your infrastructure
 
PHP7実環境ベンチ2016春
PHP7実環境ベンチ2016春PHP7実環境ベンチ2016春
PHP7実環境ベンチ2016春
 
Techtalk2015 MOD_PHP vs PHP-FPM
Techtalk2015 MOD_PHP vs PHP-FPMTechtalk2015 MOD_PHP vs PHP-FPM
Techtalk2015 MOD_PHP vs PHP-FPM
 
PHP Files: An Introduction
PHP Files: An IntroductionPHP Files: An Introduction
PHP Files: An Introduction
 

Ähnlich wie Nginx pres

Deploying nginx with minimal system resources
Deploying nginx with minimal system resourcesDeploying nginx with minimal system resources
Deploying nginx with minimal system resources
Max Ukhanov
 
Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...
Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...
Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...
MagentoImagine
 
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Atwix
 
Deploying Plack Web Applications: OSCON 2011
Deploying Plack Web Applications: OSCON 2011Deploying Plack Web Applications: OSCON 2011
Deploying Plack Web Applications: OSCON 2011
Tatsuhiko Miyagawa
 

Ähnlich wie Nginx pres (20)

Nginx [engine x] and you (and WordPress)
Nginx [engine x] and you (and WordPress)Nginx [engine x] and you (and WordPress)
Nginx [engine x] and you (and WordPress)
 
(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems
 
IT Operations for Web Developers
IT Operations for Web DevelopersIT Operations for Web Developers
IT Operations for Web Developers
 
Docker for mac & local developer environment optimization
Docker for mac & local developer environment optimizationDocker for mac & local developer environment optimization
Docker for mac & local developer environment optimization
 
Scale Apache with Nginx
Scale Apache with NginxScale Apache with Nginx
Scale Apache with Nginx
 
PHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on NginxPHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on Nginx
 
Deploying nginx with minimal system resources
Deploying nginx with minimal system resourcesDeploying nginx with minimal system resources
Deploying nginx with minimal system resources
 
10 Million hits a day with WordPress using a $15 VPS
10 Million hits a day  with WordPress using a $15 VPS10 Million hits a day  with WordPress using a $15 VPS
10 Million hits a day with WordPress using a $15 VPS
 
Magento Imagine eCommerce Conference February 2011: Optimizing Magento For Pe...
Magento Imagine eCommerce Conference February 2011: Optimizing Magento For Pe...Magento Imagine eCommerce Conference February 2011: Optimizing Magento For Pe...
Magento Imagine eCommerce Conference February 2011: Optimizing Magento For Pe...
 
Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...
Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...
Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...
 
PHP and FastCGI Performance Optimizations
PHP and FastCGI Performance OptimizationsPHP and FastCGI Performance Optimizations
PHP and FastCGI Performance Optimizations
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with Puppet
 
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
 
Setting up a local WordPress Environment
Setting up a local WordPress EnvironmentSetting up a local WordPress Environment
Setting up a local WordPress Environment
 
Zendcon scaling magento
Zendcon scaling magentoZendcon scaling magento
Zendcon scaling magento
 
How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...
How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...
How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...
 
Php through the eyes of a hoster confoo
Php through the eyes of a hoster confooPhp through the eyes of a hoster confoo
Php through the eyes of a hoster confoo
 
High Availability Content Caching with NGINX
High Availability Content Caching with NGINXHigh Availability Content Caching with NGINX
High Availability Content Caching with NGINX
 
Deploying Plack Web Applications: OSCON 2011
Deploying Plack Web Applications: OSCON 2011Deploying Plack Web Applications: OSCON 2011
Deploying Plack Web Applications: OSCON 2011
 

Kürzlich hochgeladen

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Nginx pres

  • 1. JAMES FULLER 02/13/2013 Simply Scale w/ Nginx, Memcached, PHP-FPM and APC
  • 2. In this talk... ● my experiences working in a high-traffic environment ● intro to nginx for apache users ● running php with php-fpm ● memcached & caching tips ● identifying bottlenecks / open discussion
  • 3. The Early Years Cheap Shared Hosting
  • 5. A Simple Scaling Architecture NGINX PHP-FPM MEMCACHED PHP-FPM PHP-FPM MYSQL MASTER PHP-FPM MYSQL SLAVE
  • 6.
  • 7. Apache Awesome when you need to assault your server
  • 8. The classic setup - prefork MPM w/ mod_php ● prefork is default mode prior to v2.4 ● forks (creates) new process per web resource requested ● runs php via a module (mod_php)
  • 9. Apache prefork performance killers ● Loads all modules for each forked process ● Keepalive timeout ● AllowOverride (.htaccess)
  • 10. Apache 2.4 ● Event MPM is now the default MPM in Apache 2.4 ● Event MPM designed to solve the keepalive problem ● Can talk to PHP-FPM via mod_proxy_fcgi ● Needs thread safe php
  • 11. Many reasons to keep Apache ● apache modules ● very mature software ● can tune for good results ● plays nice with nginx!
  • 13. What is NGINX? ● HTTP Server ● Reverse Proxy ● IMAP/POP3 proxy server ● Open Source
  • 14. Who is using nginx?
  • 15. Nginx performance advantages ● event based connection handling ● low/predictable memory consumption ● works well in low resource environments (VPS) ● can handle tens of thousands of concurrent requests*
  • 16. Nginx as a frontend ● serve static files ● frontend for apache for php ● no apache, via PHP-FPM ● serve content directly from memcached
  • 17. Nginx Configuration user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { server { location / { #do something } } }
  • 18. a series of blocks http { access_log /var/log/nginx/access.log main; include /etc/nginx/conf.d/*.conf; gzip on; server { server_name myserver.com www.myserver.com listen 80; location / { } } }
  • 19. server blocks server { listen 80 default_server; server_name star.yourdomain.com *.yourdomain.com; root /PATH/TO/WEBROOT; error_page 404 errors/404.html; access_log logs/star.yourdomain.com.access.log; index index.php index.html index.htm; }
  • 20. location blocks # static file 404's not logged + expires header set to maxage location ~* .(jpg|jpeg|gif|css|png|js|ico|html)$ { access_log off; expires max; } # deny htaccess location ~ /.ht { deny all; }
  • 21. PHP-FPM it's like mod_php without Apache
  • 22. PHP-FPM are you listening? ● included with php as of 5.3.3 ● runs as a daemon ○ listens for requests via socket or port (FastCGI) ● Decouple web server from executing php code
  • 23. Talking to php-fpm # pass the PHP scripts to FastCGI server # listening on 127.0.0.1:9000 location ~ .php$ { root html; fastcgi_pass 127.0.0.1:9000; #fastcgi_pass unix:/tmp/php.socket fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; include fastcgi_params; }
  • 24. Nginx for load balancing ● round robin ● least connections ● ip segmenting ● sticky backends
  • 25. upstream server upstream backend { server backend1.example.com weight=5; server backend2.example.com:8080; server unix:/tmp/backend3; } server { location / { proxy_pass http://backend; } }
  • 26. apache frontend upstream backend { server 192.168.1.2; server 192.168.1.3; server 192.168.1.4; #etc } location ~ .php$ { proxy_pass http://backend; proxy_set_header X-Real-IP $remote_addr; }
  • 27. Nginx Modules Core Log Access Map OPTIONAL Addition Secure Link Auth Basic Memcached Auto Index Degradation SSL Proxy Browser Embedded Perl Stub Status Referer Charset FLV Substitution Rewrite Empty GIF GeoIP WebDAV SCGI FastCGI Google Split Clients XSLT Geo Perftools Gzip SSI Gzip Headers Upstream Precompression Index User ID Image Filter Limit Requests uWSGI MP4 Limit Zone X-Accel Random Index Limit Conn Real IP
  • 29. What is Memcached? ● invented by Brad Fitzpatrick to solve livejournal performance problems ● distributed key value store ● super fast
  • 30. Set up Memcached instances ● small sites can use as little as 25MB ● best results and reliability in a cluster
  • 31. Talking to Memcached with PHP ● naming disaster ● php has two memcached extensions ○ memcache ○ memcached - better support for advanced features ○ wtf? ● memcache(d) php extension only on nix platforms (no windows)
  • 32. Connecting to Memcached <?php $cache = new Memcache; $cache ->addServer('192.168.1.2', 11211, ..[OPTIONS]..); $cache ->addServer('192.168.1.3', 11211, ..[OPTIONS]..); $cache ->addServer('192.168.1.4', 11211, ..[OPTIONS]..); $cache ->addServer('192.168.1.5', 11211, ..[OPTIONS]..);
  • 33. Simple Cache strategy <?php $key = 'mystash'; $data = $cache->get($key); if ($data === false) { $data = 'fill up the data'; $cache->set($key, $data, ..[OPTIONS]..); }
  • 34. Be smart about caching ● cache expensive things (network, db) ● stale content can be much worse than slow content ● have a plan to expire cache entries
  • 35. APC ● Opcode cache ● Stores ready-to-run machine code ● will eventually be replaced by zend optimizer (php 5.5) ● has data caching api
  • 36.
  • 37. Bottlenecks & Benchmarking Try to identify bottlenecks
  • 38. Find out what is slow ● web server ● database ● bandwidth / infrastructure ● php code
  • 39. Avoid the file system ● does not scale well ● expensive to make fast ● cloud hosting and multi-server implementations more complicated
  • 40. Database ● often the culprit ● choose the right technologies ● don't skimp on hardware
  • 41. Other people's benchmarks ● Monitoring and testing is key ● avoid magical thinking: ○ "Magical thinking is thinking that one's thoughts by themselves can bring about effects in the world or that thinking something corresponds with doing it" ● use tools like newrelic with actual users
  • 42. It's all about the end user ● avoid blocking javascript ● be aware of static assets ● use expires headers correctly
  • 43. Seriously, try New Relic ● FREE basic account, with PRO TRIAL ● runs as a deamon + php extension ● allows deep inspection of web transactions ● need ability to install package on server
  • 45. Dig one level deeper ● We work in abstractions ● Understand the systems that deliver your code to the browser ● Identify the problems before implementing the solutions
  • 46. Resources ● nginx wiki - http://wiki.nginx.org/ ● php-fpm - http://php.net/manual/en/install.fpm.php ● memcached - http://memcached.org/ ● memcache extensions ○ memcache - http://php.net/manual/en/book. memcache.php ○ memcache(d) - http://php.net/manual/en/book. memcached.php ● apc - http://php.net/manual/en/book.apc.php ● newrelic - http://newrelic.com/
  • 47. Questions? James Fuller @j_blotus http://www.jblotus.com