Nginx中fastcgi_pass直接写unix和使用upstream

2017-03-26 21:48:47

[开发运维 | Dev Ops] , ,

这两天虽然很忙,但是由于某些情况需要折腾一个反向代理服务器。解决了我一个困扰了很久的问题——为什么nginx不能检测后面php-fpm或者hhvm运行的状态;如果php-fpm或者hhvm挂了为什么nginx的fastcgi_cache_use_stale的参数不起作用?

我一直想当php-fpm或者hhvm挂掉的时候nginx能够提供cache的旧页面,但是fastcgi_cache_use_stale的参数似乎不起作用,今天仔细地读了一个nginx的文档。为了实现这个目的,我们需要用的是fastcgi_cache_use_stale 中 error这个参数,然而error这个参数的说明中提到了一句话

 

The error parameter also permits using a stale cached response if a FastCGI server to process a request cannot be selected.

 

仔细一想,如果你直接在fastcgi_pass使用unix://接口,直接将server弄上去,还需要什么selected?换个意思说,使用这个参数,你就必须使用 upstream 定义你的FastCGI server。尝试了一下,果然如此。

以下是配置的例子

upstream hhvm-server{
    server unix:/var/lib/hhvm/hhvm.sock;
    server unix:/var/lib/php/php-fpm.sock;
}

这里是结合了fastcgi_cache_use_stale 的配置

location ~ \.php$ {
        fastcgi_pass    hhvm-server;
        fastcgi_index   index.php;
        fastcgi_param   SCRIPT_FILENAME         $document_root$fastcgi_script_name;
        fastcgi_param   HTTPS                   on;
        include         fastcgi_params;

        fastcgi_cache_bypass $no_cache;
        fastcgi_no_cache $no_cache;
        fastcgi_cache   fastcgicache;
        fastcgi_cache_valid     200 301 302 403 404 2s;
        fastcgi_cache_min_uses  1;
        fastcgi_cache_key "$request_uri";
        fastcgi_cache_use_stale   error timeout http_500 http_503;
}

 

 

注意,fastcgi_cache_use_stale 和 proxy_cache_use_stale 相比,少了两个错误提示,一个是502,一个是504

location / {
        proxy_pass https://backend_ssl;

        proxy_set_header    Host        $host;
        proxy_set_header    X-Real-IP   $remote_addr;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;

        proxy_redirect https://$proxy_host:$proxy_port/ https://$host/;

        proxy_connect_timeout 1s;

        proxy_cache     proxycache;
        proxy_cache_valid       200 301 302 403 404 2s;
        proxy_cache_min_uses    1;
        proxy_cache_key         $scheme$host$request_uri;
        proxy_cache_use_stale   error timeout http_500 http_502 http_503 http_504;
}

 

注意这里的 proxy_connect_timeout,十分重要,要是后端关机了,这个就是连接的等待时间。

 

 

这篇博文发表在 开发运维 | Dev Ops 目录下,标签为 , ,
如需引用,请使用链接:https://note.mc256.dev/?p=1626

This article published in 开发运维 | Dev Ops with tags , , .
Cite this page using this link:https://note.mc256.dev/?p=1626

您的邮箱地址不会被公开,评论使用Gravatar头像。
Your email address will not be published. This blog is using Gravatar.

正在提交评论... Submitting ...
正在为您准备评论控件 Loading Comment Plugin
Copyright © 2013-2023 mc256. All Rights Reserved.
Powered by WordPress on top of a dual-stack k3s Cluster using JuiceFS.
Wordpress Theme Designed By mc256.
Encrypted By Let's Encrypt.  Hosted On Linode + OVH + AWS.
DNS Provided By Hostker.
Status Page by CloudFlare Worker.