Nginx или apache что лучше
Перейти к содержимому

Nginx или apache что лучше

  • автор:

Записки bаckend-разработчика

Images

Доброго времени суток, backend/frontend/full-stack/devops/qa/.. да какая разница, добро пожаловать, мой друг!

Свой цикл статей хотелось бы начать с до неприличия банальной фразы — «Все познается в сравнении». Ведь невозможно говорить о том, что какой-либо инструмент лучший, не опробовав другой. Попробуем сравнить два самых популярных в мире веб-сервера — Apache, который обслуживает около 60 млн сайтов, и Nginx — около 40 млн (больше интересной статистики тут). Возможно, после прочтения данной статьи вы сможете определиться, что лучше подходит для вашего dev-окружения. Итак, поехали! 😉

Начнем с архитектурных и функциональных отличий.

1. Метод обработки соединений с клиентами

Издавна, Apache на каждый запрос от клиента создает отдельный процесс (или поток, зависит от выбранного mpm модуля). Выглядит это следующим образом — клиент отправляет запрос, веб-сервер создает отдельный процесс на этот запрос, отвечает клиенту и блокирует процесс до тех пор, пока клиент не закроет соединение. Это легко и просто в реализации, дебаге и мониторниге, но … Как вы могли бы догадаться, если у вас highload проект, то.. дела плохи. Процесс в любой ОС требует памяти и ресурсов, а когда процессов становиться неприлично много, обработка соединений неприлично замедляется, память кончается, CPU растет. Для мелких проектов такая реализация архитектуры обработки соединений не добавит головной боли, но для высоконагруженных проектов придется ставить очень мощное железо или искать альтернативные варианты.

Nginx состоит из master-процесса и нескольких дочерних процессов. Мастер процесс обычно один — он создает дочерние процессы (воркеры, загрузчик кеша и кеш менеджер), считывает конфигурацию и открывает порты. Воркеров обычно несколько, разработчики nginx советуют количество воркеров определять равным числу ядер машины. Эти дочерние процессы буду обслуживать все соединения с клиентами в неблокирующей манере. В nginx используется бесконечный цикл, который бежит по всем соединениями и отвечает на запросы клиентов. Когда соединение закрывается, оно удаляется из event loop. Это решение идеально подходит для проектов, которые обслуживающих 10к+ соединений одновременно. При этом, загрузка CPU и использование памяти обычно равномерны, без видимых пиков.

2. Отдаваемый контент

Apache — может генерировать как статический контент, так и динамический. С этим никаких проблем нет. Прекрасно подойдет тем, кто не хочет заморачиваться с проксированием и настройкой дополнительного инструмента для генерации динамики, ведь Apache — это готовое работающее решение.

Nginx — отдает только статику и из коробки генерировать динамический контент не умеет. Если вы используете nginx и хотите генерировать динамический контент на своем сайте, то вам придется проксировать запросы тому, кто это делать умеет (apache, php-fpm и др.). Поэтому, разработчикам придется настраивать дополнительную связку, которая усложняет архитектуру, например nginx+apache (кстати в этой связке, Apache называют бекенд сервером, а Nginx — фронтендом), nginx + phpfpm, nginx + python и др.

3. Конфигурирование

Apache полюбился разработчикам и сисадминам не в последнюю очередь из-за возможности конфигурировать обработку соединений на уровне директорий. Делается это с помощью скрытого файла .htaccess, позволяющего настраивать права доступа, авторизацию, аутентификацию, политику кеширования и др правила. Это довольно-таки удобное решение для пользователей, потому что позволяет менять конфигурацию на лету, без перезагрузки сервера и без наличия доступа к основному конфигу сервера. Но также имеется маленький минус — Apache каждый раз при обработке соединений ищет файл .htacces и считывает с него информацию, что естественно замедляет выдачу ответа клиенту (кстати, поддержку настройки конфигурирования на уровне директорий можно и отключить).

Nginx не поддерживает конфигурирование на уровне каталогов. Существует один конфигурационный файл на весь проект, который обрабатывает master. Если вы хотите обновить конфигурацию, то необходимо отправить сигнал SIGHUP мастеру, который в свою очередь перезагружает конфигурацию и плавно завершает работу воркеров.

4. Работа с модулями

Apache за долгое время существования обзавелся около 60 официальными модулями, и еще большим числом неофициальных. Модули динамически подключаются, не требуют сборки и перезагрузки веб-сервера.

Nginx имеет около 130 официальных модулей. В отличие от Apache, модули Nginx не могут быть динамически загружены на лету и требуют сборки. Это гораздо сложнее, но считается безопаснее.

5. Интерпретация запросов

Apache имеет возможность интерпретировать запрос как физический ресурс в файловой системе или как URI, который требует дополнительной обработки.

Nginx создан, чтобы работать и в качестве веб-сервера, и в качестве прокси-сервера. По этой причине он работает в первую очередь с URI, транслируя их при необходимости в запросы к файловой системе.

6. Работа со скриптовыми языками

В Apache есть один модуль mod_php и все хосты вынуждены работать с одной и той же версией php и одним конфигурационным файлом.

В случае с nginx, каждый виртуалхост будет выполняться в отдельном процессе и, соответственно, может использовать разные версии php (python/ruby/perl и др.). Каждый процесс может иметь свою собственную независимую конфигурацию.

Вообще, в высоконагруженных проектах удобнее держать раздельно nginx и php. По отдельности их проще мониторить, ловить баги или узкие места. «Все-в-одном» Apache+mod_php в этом плане менее удобен.

От основных архитектурных и функциональных отличий переходим к показательным отличиям, отличиям инфрастктуры и всего того, что также является не менее важным при выборе веб-сервера.

7. Скорость работы

Скорость работы веб-сервера обычно измеряют для 2-х случаев отдачи контента: для статики и динамики. На основе тестов производительности, Nginx примерно в 2.5 раза быстрее отдает статику, чем Apache. Это довольно-таки большое превосходство. Если вам необходимо обслуживать большое количество статического контента, Nginx — лучший выбор. Во время тестирования отдачи динамического контента, Apache и Nginx показывают примерно одинаковые результаты. С точки зрения памяти, оба сервера используют один и тот же объем ресурсов. (Подробнее о тестах скорости отдачи контента можно почитать здесь)

8. Поддержка ОС

Apache прекрасно работает на Unix-подобных операционных системах, также разработчики этого веб-сервера полностью поддерживают линейку Microsoft Windows, включая последние версии этой ОС.

Nginx также поддерживает работу на множестве Unix-подобных ОС и имеет некоторую поддержку Windows, которая не является полной. Но разве кто-то в наше время размещает веб-сервер на Windows?

9. Сообщество и поддержка

Apache на рынке с 1995 года, что очень немалый срок, обеспечивший инструменту огромное сообщество и поддержку с его стороны. Практически на все вопросы на Stack Overflow уже есть исчерпывающие ответы. Коммерческой поддержки нет.

Nginx веб-сервер более молодой, на рынке он с 2004 года, что также не помешало большому сообществу сформироваться и поддерживать друг друга. Nginx, в отличие от Apache, имеет коммерческую версию Nginx Plus, которая дополнена инструментами балансировки нагрузки, мониторинга, потоковой передачи медиа и др.

10. Документация и обучение

И у Apache и у Nginx присутствует доступная официальная документация.

Nginx предлагает платное обучение, включающее в себя онлайн курсы, практические занятия и экзамен. По окончании курса все участники получают сертификаты. Например, сдать экзамен по основам nginx и получить официальный сертификат обойдется в 49$ (подробнее здесь).

От себя хотелось бы отметить, что оба решения очень стабильны, безопасны и поддерживаемы. Выбирайте то, что подходит именно вам. Пробуйте, экспериментируйте, ошибайтесь и снова пробуйте. Всем добра и будьте здоровы!

NGINX vs Apache – Choosing the Best Web Server in 2023

A web server is computer software that serves web content. It also creates a connection between a computing server and a user’s web browser, delivering files back and forth between them.

Choosing the correct web server is crucial when setting up a website or starting a VPS project since it can significantly affect a site’s performance and security.

If you’re unsure of which web server to use, consider Apache and NGINX – both are the most popular web servers and are responsible for serving over half of the traffic on the internet.

To help decide which one to start with, we will go over a detailed comparison of NGINX vs Apache.

NGINX vs Apache – General Overview

Before we start comparing Apache vs NGINX, let’s explore the differences between web servers and their general characteristics.

Apache

The Apache HTTP Server – commonly referred to as Apache or Apache HTTPD – is free, open-source web server software. It processes client requests and serves web content via Hypertext Transfer Protocol (HTTP).

Apache web server was released in 1995 and has been since maintained by the Apache Software Foundation . It was also the dominant web server on the early world wide web.

Apache HTTP Server currently powers around 33.9% of websites worldwide and holds the number one position in market share as one of the oldest web servers.

The Apache web server supports many operating systems (OS) such as Microsoft Windows, OpenVMS, and any Unix-like OS like Linux and macOS.

What’s more, the Apache web server is also part of the LAMP stack, one of the first open-source software stacks for web development. As a result, the web server also works well with many content management systems (CMS), programming languages, and web frameworks.

Apache is particularly popular due to the power and flexibility that come from its module system . With Apache’s modules, users can easily add or remove functions, modifying their server to meet their needs.

NGINX

NGINX – pronounced as “ Engine X ” – is one of the most reliable servers for scalability and speed. It’s also one of the fastest-growing web servers in the industry, having reached the number two position in market share.

Much like Apache, NGINX is open-source and free to use.

Igor Sysoev, the creator of NGINX, started developing this software in 2002 to answer the C10K problem . Back then, many web servers were not able to handle more than 10,000 connections simultaneously.

NGINX web server was released with an asynchronous and event-driven architecture, allowing many requests to process simultaneously.

NGINX is especially popular due to its ability to grow and increase traffic and be easy to scale on minimal hardware. Plus, it’s excellent at serving static files quickly.

Aside from being used as a web server, NGINX can also be utilized as a load balancer to improve a server’s resource efficiency and availability. Moreover, it can function as a reverse proxy, ensuring smooth traffic flow between servers and clients.

NGINX supports almost all Unix-like operating systems. However, installing NGINX on Windows might result in some performance limitations, like a lack of scalability and UDP authentication problems.

Now that we’ve gone over the basics of Apache and NGINX, it’s time to compare them using several critical aspects important to web servers.

Basic Architecture – Handling Connections

Web server architecture is the logical layout or mechanism determining how a web server handles web requests, connections, and traffic. It’s one of the essential criteria to consider when choosing a web server.

Let’s compare NGINX vs Apache in terms of basic architecture and how both software handle connections.

Apache

Apache follows a process-driven architecture by default, meaning it creates a single thread to handle each connection request.

The downside of process-driven architecture is that Apache needs to create many processes when dealing with a lot of requests. It can lead to heavy resource consumption , causing server issues like slow loading of web pages and site outages.

Fortunately, Apache provides various multi-processing modules (MPMs) that determine how this open-source web server accepts and handles HTTP requests, and users are free to choose which MPM suits their needs best.

There are three main MPMs:

  • mpm_prefork – the prefork MPM is not threaded, which means each child process can only handle one request at a time. However, its performance degrades immediately after the requests exceed the number of processes, making it challenging for this MPM to scale effectively.
  • mpm_worker – each process of the worker MPM can create multiple threads, and each thread can also handle a connection. This allows the system to serve multiple requests all at once. In addition, since threads need less resources than processes , this MPM can scale better and consume fewer resources than the prefork MPM.
  • mpm_event – the event MPM is similar to the worker MPM, but it’s also optimized to handle keep-alive connections . It works by putting aside dedicated threads for managing keep-alive connections and allocating active requests to other threads. This process helps the event MPM from getting slowed down by all the keep-alive requests. As a result, the Apache web server has the lowest resource requirements when used with this MPM.

Keep in mind that you can only load one MPM into your server at any time. If your project requires stability and compatibility, use the prefork MPM. For websites that need more scalability and diversity, however, consider utilizing the worker or event MPMs.

NGINX

While many web servers use a simple threaded or process‑driven architecture, NGINX goes for a different approach by utilizing asynchronous, non-blocking event-driven architecture . This enables the web server to handle multiple connections within a single process.

NGINX has a master process that performs privileged operations such as binding to ports, reading and evaluating configuration files, and creating several child processes.

Here are three types of NGINX child processes :

  • Cache loader process – can load the disk‑based cache into the memory zone. This process has low resource demands since it runs only once, right after NGINX starts.
  • Cache manager process – aims to keep the amount of cached data within the configured sizes by checking the cache periodically and removing the least recently accessed data.
  • Worker process – can handle hundreds of thousands of HTTP connections simultaneously, meaning there is no need to create new processes or threads for each connection. Instead, each worker process runs independently and contains smaller units called worker connections, and every unit is responsible for handling request threads. Worker processes can also communicate with upstream servers, as well as read and write content to disk.

The event-driven architecture of NGINX can effectively distribute client requests among worker processes, making this web server perform better than Apache when it comes to scalability.

Since NGINX can process thousands of requests without difficulties – even on low power systems – this web server is suitable for websites with high traffic levels, such as search engines, eCommerce sites, and cloud storage services. In addition, many popular content delivery networks (CDN) like MaxCDN and Cloudflare also use NGINX for content delivery.

Performance Comparison – Static vs Dynamic Content

The performance of a web server is usually determined by its ability to handle static and dynamic content.

Static content is any web file that stays the same every time it’s delivered to an end-user and is usually stored in a CDN server. Thus, it rarely changes and doesn’t depend on user behavior, making it one of the simplest content types to transmit over the internet. A few examples of static files include a JavaScript library, HTML and CSS files, and images.

Dynamic content , however, is a web page or file that changes based on the user’s interests, characteristics, and preferences. This type of content won’t look the same for everyone since it’s generated when a user requests a page. Some examples of sites with this kind of content are online stores and social media platforms.

Since NGINX and Apache come with different ways of handling requests for static and dynamic content, let’s see which web server performs better in this Apache vs NGINX comparison.

Apache

Apache serves static content by using its traditional file-based approach – this operation’s performance is primarily a function of the MPMs mentioned earlier.

Apache can also execute dynamic content within the web server itself without needing to rely on external components. Instead, it processes dynamic content by integrating a processor of suitable languages into each of its worker instances, and users can activate this processor through Apache’s dynamically loadable modules.

NGINX

When it comes to serving static content, NGINX performs faster than Apache since it caches the static files to make them available whenever they’re requested.

However, NGINX doesn’t come built-in with the capability of processing dynamic content. NGINX must pass the requests to an external processor like FastCGI Process Manager (PHP-FPM) for execution to handle and process dynamic content. Once this web server receives the content, it will transfer the results to the client.

Directory-Level Configuration for NGINX and Apache

If you want to give another user control over some components of your website, then it’s essential to pick a web server that permits directory-level configuration within its content directories.

In this NGINX vs Apache comparison, we’ll see which web server allows for directory-level configuration.

Apache

Apache supports additional configuration on a per-directory basis via .htaccess files.

The .htaccess files make it possible to let non-privileged users control specific aspects of your website without allowing them to edit the main configuration file.

That’s why many shared hosting providers use Apache to give their clients access over specific directories while still retaining control of the main configuration file.

Apache also interprets .htaccess files each time they are found along a request path, meaning they can be implemented immediately without reloading the web server.

However, there are a few downsides to using .htaccess files. One of them is that it can affect your site’s performance since Apache loads each .htaccess file for every document request. This can be a resource killer, especially for websites with a lot of traffic.

Another thing to consider before using .htaccess files is that allowing other users to modify server configuration might result in security missteps.

Thus, if you don’t need to give other parties access to your server configuration, make sure to disable .htaccess files.

NGINX

Unlike Apache, NGINX doesn’t support directory-level configuration. Though this might seem like a downside, it does work in its users’ favor as this helps to increase site performance.

Since NGINX is designed to be efficient, it doesn’t need to search for .htaccess files and interpret them, making it able to serve a request faster than Apache.

NGINX keeps your server secure by not allowing additional configuration since only someone with root permission can alter your server and site’s settings.

Modules in Apache vs Modules in NGINX

Most web servers come with a standard configuration file out-of-the-box. Sometimes, however, web developers might wish to include modules to make programming more convenient or extend the web server functionality.

Although NGINX and Apache are both extensible through a module system, the way they work differs considerably.

Apache

Apache is a customizable web server that offers more than 50 official dynamically loadable modules , which can be utilized whenever users need them. Moreover, it’s easy to find other third-party modules on the internet.

While the core features of the Apache server are always available, modules can be loaded and unloaded to modify some of the main functions of this web server.

Apache’s dynamic modules can accomplish various tasks, such as processing dynamic content, setting environment variables, and rewriting URLs.

Here are some of Apache’s most commonly used modules:

  • mod_headers – lets you control and customize HTTP request and response headers in Apache.
  • mod_expires – allows users to define expiration intervals for different types of content on websites.
  • mod_authz_host – enables access control and authorization based on the request’s hostname, IP address, or characteristics.
  • mod_mime – helps to assign content meta-information with filename extensions.
  • mod_alias – lets users inform clients that the requested URL is incorrect.

Keep in mind that Apache comes pre-built with modules and loads them into server memory. Thus, make sure to disable features that you don’t need to reduce resource consumption.

NGINX

NGINX offers more than 1 00 third-party modules to integrate within the core software. Users with a good understanding of the C language can also create NGINX modules that suit their project’s needs.

However, NGINX modules are not dynamically loadable as they need to be compiled within the core software itself. To make the modules loaded dynamically, users need to opt for the NGINX Plus .

Screenshot of the nginx website

This makes NGINX less flexible than Apache, it results in better security since integrating many dynamic modules might pose some security risks .

Security with Apache and NGINX

It’s crucial to pick a secure and reliable web server that can keep your website data safe and is regularly updated with all the latest patches.

Apache

Apache Software Foundation is actively trying to eliminate any security issues regarding its software to keep the Apache HTTP server safe. Users can subscribe to the Apache Server Announcements mailing list to stay informed of the latest updates from the software development team.

Apache also includes some configurations settings that can help to handle denial-of-service (DoS) attacks, such as:

  • TimeOut – defines the number of seconds Apache will wait for specific events before failing a request. Websites that are subject to DoS attacks should set this number as low as a few seconds.
  • RequestReadTimeout – shuts down connections from clients that don’t send their requests quickly enough.
  • KeepAliveTimeout – decides the amount of time the Apache server will wait and keep the connection open for a new request.

Keep in mind that although Apache is built to be secure and stable, your server security also depends on how you configure this server. Therefore, consider taking some additional security measures, such as installing a web application firewall (WAF).

NGINX

NGINX also offers several security controls out-of-the-box. One of them is rate-limiting, which reduces the incoming request rate to a value typical for real clients, and helps protect your server from DDoS attacks.

NGINX rate-limiting is also used to protect upstream application servers from too many user requests at once.

Besides that, NGINX users can prevent DDoS attacks by allowing or denying access based on clients’ IP addresses. This access can also be limited by password, the result of subrequest, or bandwidth.

What’s more, NGINX supports the newest version of transport layer security (TLS), which offers reliable encryption for data sent over the internet.

To get more security features, consider using NGINX Plus. With this premium version, you’ll get access to the single sign-on (SSO) function, allowing you to securely authenticate with multiple websites and applications by using one set of credentials.

Besides that, NGINX users can go to this open-source server’s website to find more security advisories and news about the latest updates.

Platform Support

Those new to the web development world should ensure that the web server they choose will provide help and support. This allows for assistance when facing an issue regarding the software.

Apache

Apache offers extensive documentation that covers various topics about this software.

It also offers community support via email, allowing users to get help from people familiar with the Apache HTTPD.

Users can also ask quick questions on Stack Overflow and the #httpd channel on the Freenode IRC network.

NGINX

To help users solve any development issues, NGINX provides a mailing list operated and moderated by the community. Besides that, it offers a public support forum to assist its users.

Due to many NGINX users, it’s also easy to find other community forums where developers share how to fix technical issues.

NGINX also provides many learning resources to help beginners learn more about this software, such as blogs, glossaries, documentation, ebooks, webinars, and datasheets.

Other than that, users who use NGINX Plus can also get dedicated support from the team, ready to assist with installation and deployment.

Choosing a Web Server

Having gone through the comparisons between NGINX vs. Apache, it’s clear that each software has both advantages and drawbacks. Thus, it’s essential to know one’s needs before deciding between NGINX or Apache.

Apache is suitable for shared hosting environments. It offers root access to modify the main configuration file, letting non-privileged users control several server aspects.

The downside is that this software can consume a lot of server memory .

As for NGINX, it has better performance than Apache when handling static content requests. It can also serve many clients at once during a high load, making it an excellent choice for a site with a large traffic volume.

Additionally, NGINX is multi-functional – users can use it as a reverse proxy, load balancer, and caching solution.

However, this software can’t serve dynamic content by default , and it needs to proxy all dynamic content requests to a back-end application server.

Remember that there are many other popular web servers to choose from, which might have more than what Apache and NGINX can offer for you specifically. Some of them are Tornado , Node.js , and Tomcat.

Can Apache and NGINX Work Together?

It’s possible to run NGINX and Apache together and take advantage of each server’s strengths – NGINX for its fast processing speed and Apache for its powerful modules.

The common practice for using both software is to place NGINX as a reverse proxy in front of Apache since it can handle hundreds of connections concurrently.

As a front-end proxy for Apache, NGINX will handle all requests from clients. For example, if it receives a request for static content, NGINX will serve the files directly to the client.

As a reverse proxy server for dynamic content, NGINX will forward the request to Apache, which will then process it and transfer the final content to the client through NGINX.

Using Apache and NGINX can reduce some blocking that usually happens when an Apache thread or process is occupied, helping boost your server performance .

Conclusion

It can be challenging to decide between Apache vs NGINX since they are both powerful in their own way. For instance, Apache provides a wide range of modules, while NGINX offers scalability and speed.

The main difference between NGINX and Apache web servers is that NGINX has event-driven architecture handling multiple requests within a single thread, while Apache is process-driven creating a thread per each request. Thus, allowing NGINX to have generally better performance.

Each software comes with its pros and cons, so deciding whether to use NGINX or Apache will depend entirely on user preferences.

Let’s recap each aspect we have compared:

  • Basic architecture – Apache creates a single thread to handle each connection request, while a single NGINX process can simultaneously take care of multiple connections.
  • Performance – NGINX performs faster than Apache in providing static content, but it needs help from another piece of software to process dynamic content requests. On the other hand, Apache can handle dynamic content internally.
  • Directory-level configuration – Apache comes with .htaccess files, allowing users to make changes to their site’s configuration without editing the main server settings. Meanwhile, NGINX doesn’t support directory-level configuration.
  • Modules – Apache’s modules can be loaded dynamically, while NGINX modules need to be compiled within the core software.
  • Security – both Apache and NGINX are secure and reliable. They also have several security tools to protect a site against DDoS attacks.
  • Support – Apache and NGINX offer community support and documentation to help beginners with any issues.

Instead of choosing either NGINX or Apache, it can be more efficient to utilize both software to improve your server performance – NGINX as a reverse proxy server for handling static content requests and Apache as the back-end to serve dynamic content.

We hope this article has helped you understand what NGINX and Apache are, the differences between the two, and when you should consider using them.

If you have any more questions regarding NGINX and Apache, please leave us a comment below.

Richard is a WordPress software developer and an expert of content management systems. When he is not playing around with code, Richard enjoys good cinema and craft beer.

Apache vs Nginx: практический взгляд

Apache vs Nginx

Apache и Nginx — 2 самых широко распространенных веб-сервера с открытым исходным кодом в мире. Вместе они обслуживают более 50% трафика во всем интернете. Оба решения способны работать с разнообразными рабочими нагрузками и взаимодействовать с другими приложениями для реализации полного веб-стека.

Несмотря на то, что у Apache и Nginx много схожих качеств, их нельзя рассматривать как полностью взаимозаменямые решения. Каждый из них имеет собственные преимущества и важно понимать какой веб-сервер выбрать в какой ситуации. В этой статье описано то, как каждый из этих веб-серверов ведет себя при различных условиях.

Общий обзор

Прежде чем погрузиться в различия между Apache и Nginx давайте бегло взглянем на предысторию каждого из этих проектов.

Apache

Apache HTTP Server был разработан Робертом Маккулом в 1995 году, а с 1999 года разрабатывается под управлением Apache Software Foundation — фонда развития программного обеспечения Apache. Так как HTTP сервер это первый и самый популярный проект фонда его обычно называют просто Apache.

Веб-север Apache был самым популярным веб-сервером в интернете с 1996 года. Благодаря его популярности у Apache сильная документация и интеграция со сторонним софтом.

Администраторы часто выбирают Apache из-за его гибкости, мощности и широкой распространенности. Он может быть расширен с помощью системы динамически загружаемых модулей и исполнять программы на большом количестве интерпретируемых языков программирования без использования внешнего программного обеспечения.

Nginx

В 2002 году Игорь Сысоев начал работу над Nginx для того чтобы решить проблему C10K — требование к ПО работать с 10 тысячами одновременных соединений. Первый публичный релиз был выпущен в 2004 году, поставленная цель была достигнута благодаря асинхронной event-driven архитектуре.

Nginx начал набирать популярность с момента релиза благодаря своей легковесности (light-weight resource utilization) и возможности легко масштабироваться на минимальном железе. Nginx превосходен при отдаче статического контента и спроектирован так, чтобы передавать динамические запросы другому ПО предназначенному для их обработки.

Администраторы часто выбирают Nginx из-за его эффективного потребления ресурсов и отзывчивости под нагрузкой, а также из-за возможности использовать его и как веб-сервер, и как прокси.

Архитектура обработки соединений

Одно из самых существенных отличий между Apache и Nginx состоит в том как они обрабатывают соединения и отвечают на различные виды трафика.

Apache

Apache предоставляет несколько модулей мультипроцессинга (multi-processing modules, MPM), которые отвечают за то как запрос клиента будет обработан. Это позволет администраторам определять политику обработки соединений. Ниже представлен список MPM-модулей Apache:

  • mpm_prefork — этот модуль создает по одному процессу с одним потоком на каждый запрос. Каждый процесс может обрабатывать только одно соединение в один момент времени. Пока число запросов меньше числа процессов этот MPM работает очень быстро. Однако производительность быстро падает когда число запросов начинает превосходить число процессов, поэтому в большинстве случаев это не самый лучший выбор. Каждый процесс потребляет значительный объем RAM, поэтому этот MPM сложно поддается масштабированию. Но он может быть использован вместе с компонентами, которые не созданы для работы в многопоточной среде. Например, PHP не является потокобезопасным, поэтому этот MPM рекомендуется использовать как безопасный метод работы с mod_php .
  • mpm_worker — этот модуль создает процессы, каждый из которых может управлять несколькими потоками. Каждый поток может обрабтывать одно соединение. Потоки значительно более эффективны чем процессы, что означает что mpm_worker масштабируется значительно лучше чем mpm_prefork. Так как потоков больше чем процессов это означает, что новое соединение может быть сразу обработано свободным потоком, а не ждать пока освободится процесс.
  • mpm_event — этот модуль похож на mpm_worker, но оптимизрован под работу с keep-alive соединениями. Когда используется mpm_worker соединение будет удерживать поток вне зависимости от того активное это соединение или keep-alive. Mpm_event выделяет отдельные потоки для keep-alive соединений и отдельные потоки для активных соединений. Это позволяет модулю не погрязнуть в keep-alive соединениях, что необходимо для быстрой работы. Этот модуль был отмечен как стабильный в Apache версии 2.4.

Nginx

Nginx появился на сцене позднее Apache, по этой причине, его разработчик был лучше осведомлен о проблемах конкурентности, с которыми сталкиваются сайты при масштабировании. Благодаря этим знаниям Nginx изначально был спроектирован на базе асинхронных неблокирующих event-driven алгоритмов.

Nginx создает процессы-воркеры каждый из которых может обслуживать тысячи соединений. Воркеры достигают такого результата благодаря механизму основанному на быстром цикле, в котором проверяются и обрабатываются события. Отделение основной работы от обработки соединений позволяет каждому воркеру заниматься своей работой и отвлекаться на обработку соединений только тогда когда произошло новое событие.

Каждое соединение, обрабатываемое воркером, помещается в event loop вместе с другими соединениями. В этом цикле события обрабатываются асинхронно, позволяя обрабатывать задачи в неблокирующей манере. Когда соединение закрывается оно удаляется из цикла.

Этот подход к обработке соединений позволяет Nginx’у невероятно масштабироваться при ограниченных ресурсах. Поскольку сервер однопоточный и он не создает процессы под каждое соединение, использование памяти и CPU относительно равномерно, даже при высоких нагрузках.

Статический и динамический контент

Если рассматривать жизненные примеры, то основные различия между Apache и Nginx в том как они обрабатывают запросы к статическому и динамическому контенту.

Apache

Apache может раздавать статический контент используя стандартные file-based методы. Производительность таких операций зависит от выбранного MPM.

Apache также может раздавать динамический контент встраивая интерпретатор нужного языка в каждого воркера. Это позволяет обрабатывать запросы к динамическому содержимому средствами самого веб-сервера и не полагаться на внешние компоненты. Интерпретаторы языков могут быть подключены к Apache с помощью динамически загружаемых модулей.

Возможность обрабатывать динамический контент средствами самого Apache упрощает конфигурирование. Нет необходимости настраивать взаимодействие с дополнительным софтом, динамический модуль может быть легко отключен в случае изменившихся требований.

Nginx

Nginx не имеет возможности самостоятельно обрабатывать запросы к динамическому контенту. Для обработки запросов к PHP или другому динамическому контенту Nginx должен передать запрос внешнему процессору для исполнения, подождать пока ответ будет сгенерирован и получить его. Затем результат может быть отправлен клиенту.

Для администраторов это означает, что нужно настроить взаимодействие Nginx с таким процессором используя один из протоколов, который известен Nginx’у (http, FastCGI, SCGI, uWSGI, memcache). Это может немного усложнить процесс настройки, в особенности когда вы будете пытаться предугадать какое число соединений разрешить, так как будет использоваться дополнительное соединение с процессором на каждый пользовательский запрос.

Однако, этот метод имеет и свои преимущества. Так как интерпретатор не встроен в каждого воркера, то оверхед, связанный с этим, будет иметь место только при запросах к динамическому контенту. Статический контент будет возвращен клиенту простым способом и запросы к интерпретатору будут выполняться только тогда когда они нужны. Apache тоже может работать в такой манере, но тогда это лишит его всех преимуществ описанных в предыдущем разделе.

Распределенная конфигурация против централизованной

Для администраторов одним из очевидных отличий этих двух веб-серверов является наличие у Apache возможности задавать конфигурацию на уровне директории.

Apache

Apache имеет опцию, которая позволяет включить конфигурирование на уровне директорий. Если эта опция включена, то Apache будет искать конфигурационные директивы в директориях с контентом в специальных скрытых файлах, которые называются .htaccess .

Так как такие конфигурационные файлы находятся в директриях с контентом, Apache вынужден при обработке каждого запроса проверять не содержит ли каждый компонент запрашиваемого пути файл .htaccess и исполнять директивы в найденных файлах. Это позволяет децентрализовать конфигурирование веб-сервера, что позволяет реализовать на уровне директорий модификацию URL’ов (URL rewrite), ограничения доступа, авторизацию и аутентификацию и даже политики кеширования.

Несмотря на то, что все описанное выше может быть настроено и в основном конфигурационном файле Apache, файлы .htaccess имеют ряд преимуществ. Во-первых, эти файлы интерпретируются как только они найдены по запрашиваемому пути, что позволяет менять конфигурацию на лету не перезагружая веб-сервер. Во вторых, это позволяет дать возможность непривилегированным пользователям контролировать определынные аспекты собственных веб-приложений с помощью .htaccess .

Это дает простой способ таким приложениям как системы управления контентом (CMS) конфигурировать собственное окружение не имея доступа к конфигурационному файлу веб-сервера. Это также может быть использовано шаред хостингами, чтобы сохранить контроль над основным конфигурационным файлом и дать клиентам контроль над конфигурацией определенных директорий.

Nginx

Nginx не интерпретирует файлы .htaccess и не предоставляет механизм конфигурирования на уровне директорий за пределами основного конфигурационного файла. Этот подход может показаться менее гибким чем в случае с Apache, но он имеет свои преимущства.

Основное преимущество перед использованием .htaccess — это улучшенная производительность. Типичная установка Apache позволяет использовать файлы .htaccess в любой директории, поэтому веб-сервер при каждом запросе вынужден проверять наличие этого файла во всех родительских директориях запрошенного файла. Если найден один или более таких файлов, то все они должны быть прочитаны и интерпретированы.

Так как Nginx не позволяет переопределять конфиги на уровне директорий, он может обрабатывать запросы быстрее, ведь ему достаточно сделать один directory lookup и прочитать один конфигурационный файл на каждый запрос (предполагается, что файл найден там где он должен быть по соглашению).

Второе преимущество связано с безопасностью. Распределенная конфигурация на уровне директорий в Apache возлагает ответственность за безопасность на обычных пользователей, которые вряд ли способны решить эту задачу качественно. То что администратор контролирует весь сервер предотвращает ошибки безопасности, которые могут возникнуть если дать пользователям доступ к конфигурации.

Имейте ввиду, что вы можете отключить поддержку .htaccess в Apache, если сказанное выше произвело на вас впечатление.

Интерпретация базирующаяся на файлах и URI

То как веб-сервер интерпретирует запрос и сопоставляет его с ресурсом в системе это еще одна отличительная особенность в этих двух серверах.

Apache

Apache имеет возможность интерпретировать запрос как физический ресурс в файловой системе или как URI, который требует дополнительной обработки. Первый тип запросов использует конфигурационные блоки <Directory> или <File> , второй — блоки <Location> .

Так как Apache изначально был спроектирован как веб-сервер, он по умолчанию интерпретирует запросы как ресурсы в файловой системе. Он берет document root веб-сервера и дополняет его частью запроса, которая следует за именем хоста и номером порта, чтобы найти запрашиваемый файл. В общем случае, иерархия файловой системы представленная в вебе доступна как дерево документов.

Apache предоставляет ряд альтернатив на случай когда запрос не соответствует файлу в файловой системе. Использование блоков <Location> это метод работы с URI без отображения на файловую систему. Также возможно использовать регулярные выражения, которые позволяют задать более гибкие настройки для всей файловой системы.

Так как Apache может оперировать и c файловой системой, и с webspace, то он в основном опирается на методы работы с файловой системой. Это видно в некоторых решениях в дизайне архитектуры веб-сервера, например, в использовании файлов .htaccess для конфигурирования на уровне директорий. Документация к Apache не рекомендует использовать URI-блоки для ограничения доступа для запросов к файловой системе.

Nginx

Nginx создан, чтобы работать и в качестве веб-сервера, и в качестве прокси-сервера. По этой причине он работает в первую очередь с URI, транслируя их при необходимости в запросы к файловой системе.

Эта особенность прослеживается в том как для Nginx конструируются и интерпретируются конфигурационные файлы. В Nginx нет способа создать конфигурацию для заданной директории, вместо этого он парсит URI.
Например, основными конфигурационными блоками в Nginx являются <server> и <location> . В блоке <server> определяется хост, который будет обслуживаться, блок <location> отвечает за обработку части URI, которая идет после имени хоста и номера порта. Таким образом, запрос интерпретируется как URI, а не как путь в файловой системе.

В случае запросов к статическим файлам все запросы должны быть отображены (mapped) на путь в файловой системе. Сначала Nginx выбирает блоки server и location, которые будут использованы для обработки запроса и затем объединяет document root с URI, в соответствии с конфигурацией.

Эти подходы (интерпретация запроса как пути в файловой системе и как URI) могут показаться похожими, но тот факт что Nginx рассматривает запросы как URI, а не как пути в файловой системе позволяет ему легче справляться одновременно и с ролью веб-сервера, и с ролью прокси. Nginx конфигурируется так, чтобы отвечать на различные шаблоны запросов. Nginx не обращается к файловой системе до тех пор пока он не готов обслужить запрос, что объясняет почему он не реализует ничего похожего на файлы .htaccess .

Модули

И Apache, и Nginx могут быть расширены при помощи системы модулей, но способы реализации модульной системы принципиально отличаются.

Apache

Система модулей Apache позволяет динамически загружать и выгружать модули, чтобы удовлетворить ваши потребности, в то время как ваш сервер запущен. Ядро Apache всегда доступно, в то время как модули можно включать и выключать, чтобы добавить или удалить функциональность из основного сервера.

Apache использует эту функциональность для решения широкого круга задач. Благодаря зрелости платформы существует огромное множество модулей, которые могут изменять ключевые особенности сервера, например модуль mod_php позволяет включать PHP-интерпретатор в кажого воркера.

Использование модулей не ограничивается лишь обработкой динамических запросов. Среди других возможностей модулей: изменение URL’ов (URL rewrite), аутентификация клиентов, защита сервера, логгирование, кеширование, сжатие, проксирование, ограничение частоты запросов, шифрование. Динамические модули могут значительно расширить функцональность ядра.

Nginx

Nginx тоже имеет систему модулей, но она сильно отличается от подхода используемого в Apache. В Nginx модули загружаются не динамически, а должны быть выбраны и скомпилированы с ядром сервера.

Для многих пользователей по этой причине Nginx кажется менее гибким. Это особенно относится к пользователям, кто имеет мало опыта ручной сборки приложений и предпочитают использовать системы управления пакетами. Обычно разработчики дистрибутивов стремятся создать пакеты для всех часто используемых модулей, но если вам нужен какой-то нестандартный модуль вам придется собрать его из исходников самостоятельно.

Тем не менее, модули в Nginx очень полезны и востребованы, вы можете определить чего вы хотите от сервера и включить только те модули, что вам нужны. Некоторые пользователи считают такой подход более безопасным так как произвольные модули не могут быть подключены к серверу.

Модули Nginx реализуют те же возможности, что и модули Apache: проксирование, сжатие данных, ограничение частоты запросов, логгирование, модификация URL’ов, гео-локация, аутентификация, шифрование, потоковое вещание, почтовые функции.

Поддержка, совместимость, экосистема и документация

В процессе использования приложения важными являются экосистема созданная вокруг него и возможность получения поддержки.

Apache

Так как Apache пользуется популярностью такое длительное время с поддержкой у него нет проблем. Легко можно найти большое количество документации как от разработчиков Apache, так и от сторонних авторов. Эта документация покрывает все возможные сценарии использования Apache, включая взаимодействие с другими приложениями.

Существует много инструментов и веб-проектов идущих в комплекте со средствами запуска самих себя из под Apache. Это относится как к самим проектам, так и к системам управления пакетами.

В общем случае Apache будет иметь больше поддержки в сторонних проектах просто потому он доступен на рынке длительное время. Администраторы также обычно имеют больше опыта работы с Apache, так как большинство людей начинают работу с шаред-хостингов где Apache более популярен из-за поддержки файлов .htaccess .

Nginx

Nginx обычно используется там, где предъявляются повышенные требования к производительности и в некоторых областях он все еще является догоняющим.

В прошлом было сложно найти вменяемую поддержку по этому веб-серверу на английском языке, так как на ранних этапах разработка и документация велись на русском языке. Вместе с ростом интереса к проекту документация была переведена на английский и теперь можно найти достаточное количество документации и от разработчиков веб-сервера, и от сторонних авторов.

Разработчики стороннего ПО также начинают поддерживать работу с Nginx и некоторые из них уже предлагают на выбор пользователя конфиги для работы или с Apache, или с Nginx. И даже без поддержки приложением работы с Nginx не составляет большого труда написать свой конфиг для интеграции приложения с Nginx.

Совместное использование Apache и Nginx

После того как вы ознакомились с плюсами и минусами Apache и Nginx у вас должно появиться представление того, какой из серверов больше подходит под ваши задачи. Однако, можно достигнуть лучших результатов используя оба сервера вместе.

Распространенной схемой использования является размещение Nginx перед Apache в качестве реверс-прокси. В такой конфигурации Nginx называют фронтендом, а Apache — бэкендом. При таком подходе Nginx будет обслуживать все входящие запросы клиентов и мы получим выигрыш из-за его возможности обрабатывать множество конкурентных запросов.

Nginx будет самостоятельно обслуживать статический контент, а для динамического контента, например для запросов к PHP-страницам, будет передавать запрос к Apache, который будет рендерить страницу, возвращать ее Nginx’у, а тот в свою очередь будет передавать ее пользователю.

Такая конфигурация очень популярна, Nginx используется в ней для сортировки запросов. Он обрабатывает сам те запросы которые может и передает Apache только запросы, которые не может обслужить сам, снижая таким образом нагрузку на Apache.

Эта конфигурация позволяет горизонтально масштабировать приложение: вы можете установить несколько бэкенд серверов за одним фронтендом и Nginx будет распределять нагрузку между ними, увеличивая тем самым отказоустойчивость приложения.

Заключение

Как вы можете видеть и Apache, и Nginx — это мощные, гибкие и функциональные инструменты. Для того чтобы выбрать сервер под ваши задачи необходимо определиться с требованиями к нему и провести тесты на всех возможных паттернах использования вашего приложения.

Между этими проектами есть значительные различия, которые могут оказать влияние на производительность, возможности и время реализации необходимое для внедрения и запуска каждого из решений. Выбор является серией компромиссов и не стоит пренебрегать тестами. В конечном итоге, не существует одного универсального веб-сервера под все возможные задачи, поэтому важно найти решение максимально соответствующее вашем задачам и целям.

NGINX vs. Apache: Our View of a Decade-Old Question

The Apache HTTP server and NGINX are the two most popular open source web servers powering the Internet today. When Igor Sysoev began working on NGINX over 10 years ago, no one expected that the project he created for the purpose of accelerating a large Apache‑based service would grow to have the influence it has now.

Apache HTTP server is a solid platform for almost any web technology developed over the last 20 years, but time is showing that the architectural decisions made when the code was first laid down are becoming limiting factors in its suitability for modern web demands.

In this article, I’ll share my perspective on these changes and limitations, and explain how a modern web developer can respond. I write this as a very early user of Apache (and of NCSA’s httpd before that), as someone who wrote CGI scripts in bash and Perl before PHP was anywhere near mainstream, and as a one‑time software engineer at Zeus, one of the very first event‑driven web servers to challenge the Apache model of doing things. My belief is absolutely not that Apache is unfit for purpose, but that in the face of modern web applications, it is now dated and needs support in order to function effectively.

The Key to Apache’s Early Success

Apache was the backbone of the first generation of the World Wide Web, becoming the industry standard for web serving almost as soon as it debuted in 1995. It was created at a time when the World Wide Web was still a novelty. Traffic levels were low, web pages were simple, bandwidth was constrained and expensive, and CPU was relatively cheap. There was a huge thirst in the early community to innovate with new technologies, and Apache was the platform of choice.

Architectural Simplicity

The simplicity of Apache’s architectural model was key to its early success. At that time, many network services were triggered from a master service called inetd ; when a new network (TCP) connection was received, inetd would fork ( ) and exec ( ) a Unix process of the correct type to handle the connection. The process read the request on the connection, calculated the response and wrote it back down the connection, and then exited.

Apache took this model and ran with it. The biggest downside was the cost of forking a new httpd worker process for each new connection, and Apache developers quickly adopted a prefork model in which a pool of worker processes was created in advance, each ready and willing to accept one new HTTP connection.

When a prefork Apache web server received an HTTP connection, one of the httpd worker processes grabbed and handled it. Each process handled one connection at a time, and if all of the processes were busy, Apache created more worker processes to be ready for a further spike in traffic.

Easy to Develop, Easy to Innovate

The isolation and protection afforded by the one‑connection‑per‑process model made it very easy to insert additional code (in the form of modules) at any point in Apache’s web‑serving logic. Developers could add code secure in the knowledge that if it blocked, ran slowly, leaked resources, or even crashed, only the worker process running the code would be affected. Processing of all other connections would continue undisturbed.

Apache quickly became the dominant web server on the early World Wide Web. Its adoption at websites grew steadily, peaking at over 70% market share at the end of 2005.

Netcraft November 2005 Web Server Survey

Source: Netcraft November 2005 Web Server Survey

Challenged by the Growth of the World Wide Web

Over the past 20 years, there has been explosive growth in the volume of traffic and the number of users on the World Wide Web.

webgrowth-traffic-users

At the same time, the weight of web pages (the size and number of components the web browser has to fetch to render a page) has grown steadily, and users have become less and less patient about waiting for web pages to load.

webgrowth-weight-wait

(For more details about these changes, check out the list of resources for Internet statistics at the end of this post.)

All of these changes presented a real challenge to Apache’s process‑per‑connection model, which did not scale well in the face of high traffic volume and heavy pages (more embedded resources requiring more HTTP requests).

Web Clients Greedily Use Resources

To decrease page‑rendering time, web browsers routinely open six or more TCP connections to a web server for each user session so that resources can download in parallel. Browsers hold these connections open (a practice called HTTP keepalive) for a period of time to reduce delay for future requests the user might make during the session. Each open connection exclusively reserves an httpd process, meaning that at busy times, Apache needs to create a large number of processes.

multiprocess

Running lots of processes consumes lots of memory. Excessive consumption results in thrashing and large numbers of context switches, which can slow the web server to a crawl.

Admins Fought Against Clients to Recover Resources

To mitigate the performance problems of the prefork Apache server, admins were encouraged to adopt two measures. They limited the maximum number of httpd processes (typically to 256) to avoid exhausting server resources; as a result, when the number of concurrent TCP connections exceeds the number of processes, new connections are stalled indefinitely. Admins also disabled keepalive connections or reduced their duration, in order to free up httpd processes more quickly.

Both of these measures have a detrimental effect on the user experience, causing web pages to load more slowly and less reliably.

The Apache Team Implemented Alternative MPMs

To improve portability and scalability on some platforms, Apache’s core developers created two additional processing models (called multi‑processing modules, or MPMs).

The worker MPM replaced separate httpd processes with a small number of child processes that ran multiple worker threads and assigned one thread per connection. This was helpful on many commercial versions of Unix (such as IBM’s AIX) where threads are much lighter weight than processes, but is less effective on Linux where threads and processes are just different incarnations of the same operating system entity.

Apache later added the event MPM (not to be confused with NGINX’s event‑driven architecture), which extends the worker MPM by adding a separate listening thread that manages idle keepalive connections once the HTTP request has completed.

Apache’s Heavyweight, Monolithic Model Has Its Limits

These measures go some way to improving performance, but the monolithic one‑server‑does‑all model that was key to the early success of Apache has continued to struggle as traffic levels increase and web pages become richer and richer. Performance in lab benchmarks is often not replicated in live production deployments at busy websites, and tuning Apache to cope with real‑world traffic is a complex art. Somewhat unfairly, Apache has gained a reputation as a bloated, overly complex, and performance‑limited web server that can be exploited by slow denial‑of‑service (DoS) attacks.

Introducing NGINX – Designed for High Concurrency

NGINX was written specifically to address the performance limitations of Apache web servers. It was created in 2002 by Igor Sysoev, a system administrator for a popular Russian portal site (Rambler.ru), as a scaling solution to help the site manage greater and greater volumes of traffic. It was open sourced in October 2004, on the 47th anniversary of the launch of Sputnik.

NGINX can be deployed as a standalone web server, and as a frontend proxy for Apache and other web servers. This drop‑in solution acts as a network offload device in front of Apache servers, translating slow Internet‑side connections into fast and reliable server‑side connections, and completely offloading keepalive connections from Apache servers. The net effect is to restore the performance of Apache to near the levels that administrators see in a local benchmark.

NGINX also acts as a shock absorber, protecting vulnerable Apache servers from spikes in traffic and from slow‑connection attacks such as Slowloris and slowhttprequest.

The Secret’s in the Architecture

The performance and scalability of NGINX arise from its event‑driven architecture. It differs significantly from Apache’s process‑or‑thread‑per‑connection approach – in NGINX, each worker process can handle thousands of HTTP connections simultaneously. This results in a highly regarded implementation that is lightweight, scalable, and high performance.

associated-words-nginx-survey-2015

A downside of NGINX’s sophisticated architecture is that developing modules for it isn’t as simple and easy as with Apache. NGINX module developers need to be very careful to create efficient and accurate code, without any resource leakage, and to interact appropriately with the complex event‑driven kernel to avoid blocking operations. As a result, the success of the NGINX project has rested heavily on the core development team employed by NGINX, Inc., the company founded by Igor Sysoev in 2011 to ensure the future of the NGINX Open Source.

The announcement at nginx.conf 2015 of future support for dynamic modules marks the next stage of a third‑party developer ecosystem, with fewer barriers to entry than the earlier compile‑in architecture.

Editor – NGINX Plus Release 11 (R11) and NGINX Open Source 1.11.5 introduce binary compatibility for dynamic modules, including support for compiling custom and third‑party modules.

NGINX and Apache – A Good Starting Point

For many application types, NGINX and Apache complement each other well, so it’s often more apt to talk about “NGINX and Apache” instead of “NGINX vs. Apache”. A very common starting pattern is to deploy NGINX Open Source as a proxy (or NGINX Plus as the application delivery platform) in front of an Apache‑based web application. NGINX performs the HTTP‑related heavy lifting – serving static files, caching content, and offloading slow HTTP connections – so that the Apache server can run the application code in a safe and secure environment.

NGINX provides all of the core features of a web server, without sacrificing the lightweight and high‑performance qualities that have made it successful, and can also serve as a proxy that forwards HTTP requests to upstream web servers (such as an Apache backend) and FastCGI, memcached, SCGI, and uWSGI servers. NGINX does not seek to implement the huge range of functionality necessary to run an application, instead relying on specialized third‑party servers such as PHP‑FPM, Node.js, and even Apache.

Apache is like Microsoft Word. It has a million options but you only need six. NGINX does those six things, and it does five of them 50 times faster than Apache.

For this reason, the market share of NGINX has grown steadily over recent years, as reported in surveys from Netcraft and W3Techs.

Netcraft September 2015 Web Server Survey

Source: Netcraft September 2015 Web Server Survey

top-sites-w3techs

(Note that these surveys just detect the software that handles incoming Internet traffic and stamps outgoing responses with an identifying Server header. They don’t offer much insight into what software and platforms lie within an application.)

And so emerged the architectural pattern of running NGINX at the frontend to act as the accelerator and shock absorber, and whatever technology is most appropriate for running applications at the backend.

Modern Web Applications are Very Different From the LAMP Stacks of the Past

You might have heard the buzz around containers, microservices, and lightweight application frameworks such as Node.js and Python/uWSGI.

We are seeing significant changes in the ways that modern web applications are built:

monolithic-to-dynamic

Underlying these changes is a desire to achieve faster time‑to‑market for new web applications and features, by moving away from heavy, monolithic architectures to more loosely coupled, distributed architectures. Continuous delivery is the fundamental driving force behind this shift.

NGINX Delivers Microservices Applications

Containerized and microservices applications require a stable and reliable frontend that conceals the complexity and ever‑changing nature of the application behind it.

To forward HTTP requests to upstream application components, the frontend needs to provide termination of HTTP, HTTPS, and HTTP/2 connections, along with “shock‑absorber” protection and routing. It also needs to offer basic logging and first‑line access control, implement global security rules, and offload HTTP heavy lifting (caching, compression) to optimize the performance of the upstream application.

This is where NGINX and NGINX Plus come into their element, providing these twelve features (among others) that make them ideal for microservices and containers:

  • Single, reliable entry point
  • Serve static content
  • Consolidated logging
  • SSL/TLS and HTTP/2 termination
  • Support multiple backend apps
  • Easy A/B testing
  • Scalability and fault tolerance
  • Caching (for offload and acceleration)
  • GZIP compression
  • Zero downtime
  • Simpler security requirements
  • Mitigate security and DDoS attacks

Use NGINX to Give Consistency Within Each Containerized Service

Modern, distributed web applications can use a mix of diverse application components, and it’s not uncommon for them to combine a number of different technologies and platforms. The common requirement is that each component be lightweight and scalable, suitable for deploying in containers on a resource‑constrained multitenant server.

Many containers don’t need an embedded web server. They deliver their service using the framework’s own simple HTTP frontend, or using protocols such as FastCGI or uWSGI. In some cases, however, a robust and lightweight web server is required – for example, for efficiency, logging, security, monitoring, or additional functionality. The lightweight nature of NGINX makes it a much better choice to insert in a container than the Apache monolith.

NGINX serves as gateway and embedded web server in a microservices application architecture

NGINX as gateway and embedded web server in a microservices application architecture

Conclusion

Apache and NGINX both have their place, and NGINX is clearly in the ascendency. Your requirements and experience might lead you to chose one or both, or even a different path.

A monolithic architectural framework was sound practice when Apache was new and fresh, but app developers are finding that such an approach is no longer up to the task of delivering complex applications at the speed their businesses require. Microservice architecture is emerging as the wave of the future for web apps and sites, and NGINX is perfectly poised to assume its place in that architecture as the ideal application delivery platform for the modern Web.

Resources for Internet Statistics

Cisco’s Visual Networking Index (links to historical reports and forecasts on dozens of statistics)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *