search
HomeBackend DevelopmentPHP TutorialNginx dynamic upstreams implementation, nginxupstreams_PHP tutorial

Nginx 动态 upstreams 实现,nginxupstreams

我最近在工作中做一个设置,我有一个面向用户的 Nginx 服务,它将访问转发到运行在AWS Elastic Load Balancer (如你所知. ELB)上的一个服务。这本身似乎不是一个困难的任务,你只需要找到 ELB 的主机名,将 ngin x指向它,这样不就搞定了,对吧?

location / {
    proxy_pass http://service-1234567890.us-east-1.elb.amazonaws.com;
}

测试没有问题,再正确设置一下防火墙/安全组配置,它就应该可以很好的工作了。几个小时之后,你可能会发现,服务不再工作了,尽管没有做任何改变。直接访问 ELB 端点是可以工作的,但访问 Nginx 却总是超时提醒。

ELB端启蒙

为了弄清楚为什么服务突然中止,需要先了解一下 ELB 是如何工作的:

当你创建一个弹性负载均衡(Elastic Load Balancer),你将会得到 DNS 的返回记录,AWS 会告诉你所有在使用的访问服务。DNS 记录是一个轮询 DNS(round robin DNS)记录,它指向两个或更多的 IP 地址——这取决于你有多少可用的区域。DNS 记录被设置成 60 秒的存活时间(time to live),这意味几乎不会有记录缓存。

短 TTL 可以让 AWS 快速改变机器的运行负载,在不中断服务的情况下,不会有任何复杂的虚拟 IP 问题。这也是他们特别告诉你不要查找主机名和发送流量到其中某个 IP 地址的原因,那样的话,你的服务可能会在未来某个未定义的时间,IP 地址可能会停止为负载均衡工作。

回到 Nginx

问题在于,对于 Nginx 来说,当它读取到一个配置时,它就会立刻向 DNS 请求主机名,然后使用其结果,直到下次重新加载配置。在这段时间到来之前,ELB 可能改变 IP 地址,让你的 Nginx 把请求转发到一些不为你服务的地址。

Nginx Plus

解决这个问题的方式是为 Nginx Plus 付费,它添加 resolve 标记对在 upstream 分组上的服务器进行指示。那就是让 Nginx 骄傲的 DNS 对 TTL 的记录,偶尔按顺序重新处理记录,并取得服务器使用的更新列表。

为这个功能花费每年每服务器 $1.500,看起来花费很多。当然这是你希望得到 Nginx Plus 带来的其他功能,如果你不需要它们,这将会是一个昂贵的升级。

免费的选择

一个更加实惠的选择是写这样一个配置:

resolver 172.16.0.23;
set $upstream_endpoint http://service-1234567890.us-east-1.elb.amazonaws.com;
location / {
    proxy_pass $upstream_endpoint;
}

它将会生效并且 Nginx 会遵循记录 DNS 记录的 TTL,万一一个请求进来,会重新解释它而且缓存的记录会过期。为什么会这样?

答案可以在 proxy_pass 指令文档结尾找到,它声明了:

<p>服务器名,端口以及传递的URI也可以使用变量被指定:</p>
<pre class="code">proxy_pass http://$host$uri;

甚至像这样:

proxy_pass $request;

在这个案例中,服务器名会在所描述的 server groups 中被查找,如果没找到,会使用 resolver 来决定.

当我们给 proxy_pass 提供一个变量的时候,我们基本上是利用其改变行为,但这样确实需要我们在配置中指定一个 DNS resolver。例子里边用到的 DNS resolver应该能够在 AWS 上面跑在默认 VPC或者 EC2 中的所有服务器工作(适用)。你也可以随时查看 /etc/resolv.conf 找出哪些 AWS 为你的服务器提供并使用了哪些 DNS 服务器。

关于转发 URI 的 Caveat(警告)

如果你在 Nginx 中设置的 Location 不只是 /,那么你需要注意到当给定一个变量作为参数时,proxy_pass 细微的改变行为。

先说重要的,快速概括 proxy_pass 如何在正常在操作中工作:

正常的表现行为

设想我们有一个 Nginx 配置包括这些:

location /foo/ {
    proxy_pass http://127.0.0.1:8080;
}

当我们发送一个 /foo/bar/baz 的请求到这个站点,Nginx 会转发请求到 http://127.0.0.1:8000/foo/bar/baz。

location /foo/ {
    # Note the trailing slash       &darr;
    proxy_pass http://127.0.0.1:8080/;
}

Nginx 会在 Location 记录里边去掉部分指定的 URI,然后把剩下的部分传给 upstream 服务器。所以请求 /foo/bar/baz 会被转发到 http://127.0.0.1:8080/bar/baz。

改变行为

当我们使用一个变量作为 proxy_pass 的参数的时候,上面带有尾部斜杠的行为会改变。例如我们有这样的配置。

resolver 172.16.0.23;
set $upstream_endpoint http://service-1234567890.us-east-1.elb.amazonaws.com/;
location /foo/ {
    proxy_pass $upstream_endpoint;
}

当我们向那个配置发送请求 /foo/bar/baz,转发请求将不会去到/并且不是预想中的 /bar/baz。

为此解决方案就是从 upstream 的 endpoint 去掉尾部斜杠,然后像这样手动重写:

resolver 172.16.0.23;
set $upstream_endpoint http://service-1234567890.us-east-1.elb.amazonaws.com;
location /foo/ {
    rewrite ^/foo/(.*) /$1 break;
    proxy_pass $upstream_endpoint;
}

然后当你发送请求 /foo/bar/baz,upstream 会接受到我们想要的请求 /bar/baz。

Conclusion

You must know that this is not only applicable to setting up elb as an upstream server, it is also applicable to all configurations of modifying the DNS configuration of nginx as an upstream server.

Hope this is useful, if you have any suggestions or just want to simply contact me, hit me up on twitter Tenzer.

Do programmers have to work overtime? NO!

I know that coders want to get rid of the title of overtime dog and takeaway face, so we are here!

We made an APP that allows programmers to share knowledge and skills, and we think it can subvert the way programmers work
!

Some people say we are wishful thinking, but we don’t think so.

In order to inflame the faces of those who accuse us of our wishful thinking, we are in urgent need of powerful figures in the programmer industry to
our "pulse"! The "diagnosis fee" is generous! After all, we are not short of money, we just want to do our best!

According to the Quanquan Dictionary, Niubi-character refers to a QQ group owner with more than 1,000 group members or a Tieba owner with more than
2,000 followers Or a Weibo blogger with more than 10,000 followers or a moderator with more than 2,000 topic posts
or a blogger with more than 2,000 single post views or a celebrity with a super wide network of connections people.

To the future greats who have failed to meet the standards, we can only say with tears: Odd, we have a long time to come, can we not make an appointment this time? When you become a god one day, I will depend on you for life and death!
Come? Still not coming?

Circle interaction password: 1955246408 (QQ)

http://www.bkjia.com/PHPjc/1048746.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1048746.htmlTechArticleNginx dynamic upstreams implementation, nginxupstreams I recently made a setup at work, I have a user-oriented Nginx service, It forwards access to Bala running on AWS Elastic Load...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor