Меню

No live upstreams while connecting to upstream nginx ошибка

I have a really weird issue with NGINX.

I have the following upstream.conf file, with the following upstream:

upstream files_1 {
    least_conn;
    check interval=5000 rise=3 fall=3 timeout=120 type=ssl_hello;

    server mymachine:6006 ;
}

In locations.conf:

location ~ "^/files(?<command>.+)/[0123]" {
        rewrite ^ $command break;
        proxy_pass https://files_1 ;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

In /etc/hosts:

127.0.0.1               localhost               mymachine

When I do: wget https://mynachine:6006/alive --no-check-certificate, I get HTTP request sent, awaiting response... 200 OK. I also verified that port 6006 is listening with netstat, and its OK.

But when I send to the NGINX file server a request, I get the following error:

no live upstreams while connecting to upstream, client: .., request: «POST /files/save/2 HTTP/1.1, upstream: «https://files_1/save»

But the upstream is OK. What is the problem?

502 bad gateway error displayed when switching between site pages and some times on home page but not for the first request on the home page it is only when another page redirect to it. and it happens for some javascript files

load balancing configured on two upstreams php1 php2 both are apache server.

When I checked error log i fond:

no live upstreams while connecting to upstream

[error] 27212#0: *314 no live upstreams while connecting to   upstream, client: ip_address , server: example.com, request: "GET / HTTP/1.1", upstream: "http://example.com", host: "example.com", referrer: "http://example.com/mypages/"

and this is load balancing server configuration

  upstream example.com  {
    #  ip_hash;
      server php01 max_fails=3 fail_timeout=15s;
      server php02 max_fails=3 fail_timeout=15s;
    }

    server {
      listen IP:80;
      server_name example.com;
      access_log /var/log/nginx/example.com.access;
      error_log /var/log/nginx/example.com.error error;

     location / {
        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_set_header X-Forwarded-Proto $scheme;
        proxy_pass  http://$server_name/$uri;
        proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;
        proxy_cache_bypass $http_pragma $http_authorization;
        proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
        proxy_no_cache $http_pragma $http_authorization;
      }

    }

I searched for hours and nothing helpful found my streams are up and no problems with them.

I am trying to run an image using the nginx-proxy image. I created the following docker-compose.yml file to make executing the commands easier

version: '3.4'
services:
  nginx-proxy:
    image: jwilder/nginx-proxy
    container_name: nginx-proxy
    ports:
      - 80:80
      - 443:443
    restart: always
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
      - /etc/certificates:/etc/nginx/certs

  private_package_name:
    image: crestapps/private_package_name:latest
    container_name: private_package_name
    command: tail -f /dev/null
    environment:
      - VIRTUAL_HOST=private_package_name.crestapps.com
      - VIRTUAL_PORT=51736
      - ASPNETCORE_ENVIRONMENT=Development
    ports:
      - 51736:80
      - 44344:443
    volumes:
      - /app/storage:/storage

When I run docker-compose up, both apps run as expected. However, when I make a request to https://private_package_name.crestapps.com I get

502 Bad Gateway

When I look at the logs I see the following

nginx-proxy          | nginx.1    | 2020/01/20 23:49:40 [error] 42#42: *1 no live upstreams while connecting to upstream, client: PersonalIpAddress, server: private_package_name.crestapps.com, request: "GET / HTTP/2.0", upstream: "http://private_package_name.crestapps.com/", host: "private_package_name.crestapps.com"
nginx-proxy          | nginx.1    | private_package_name.crestapps.com PersonalIpAddress - - [20/Jan/2020:23:49:40 +0000] "GET / HTTP/2.0" 502 157 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0"
nginx-proxy          | nginx.1    | 2020/01/20 23:49:41 [error] 42#42: *1 no live upstreams while connecting to upstream, client: PersonalIpAddress, server: private_package_name.crestapps.com, request: "GET /favicon.ico HTTP/2.0", upstream: "http://private_package_name.crestapps.com/favicon.ico", host: "private_package_name.crestapps.com"
nginx-proxy          | nginx.1    | private_package_name.crestapps.com PersonalIpAddress - - [20/Jan/2020:23:49:41 +0000] "GET /favicon.ico HTTP/2.0" 502 157 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0"

When I execute docker ps I get the following

CONTAINER ID        IMAGE                                COMMAND                  CREATED              STATUS              PORTS                                           NAMES
d661d4bff1f3        crestapps/private_package_name:latest   "tail -f /dev/null"      9 seconds ago        Up 6 seconds        0.0.0.0:51736->80/tcp, 0.0.0.0:44344->443/tcp   private_package_name
0bd0da4141f8        jwilder/nginx-proxy                  "/app/docker-entrypo…"   About a minute ago   Up About a minute   0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp        nginx-proxy

running docker logs nginx-proxy gives me the following

WARNING: /etc/nginx/dhparam/dhparam.pem was not found. A pre-generated dhparam.pem will be used for now while a new one
is being generated in the background.  Once the new dhparam.pem is in place, nginx will be reloaded.
forego     | starting dockergen.1 on port 5000
forego     | starting nginx.1 on port 5100
dockergen.1 | 2020/01/21 00:00:51 Generated '/etc/nginx/conf.d/default.conf' from 2 containers
dockergen.1 | 2020/01/21 00:00:51 Watching docker events
dockergen.1 | 2020/01/21 00:00:51 Contents of /etc/nginx/conf.d/default.conf did not change. Skipping notification 'nginx -s reload'
2020/01/21 00:01:08 [notice] 53#53: signal process started
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
dhparam generation complete, reloading nginx
dockergen.1 | 2020/01/21 00:02:27 Received event die for container 274d6e739fd8
dockergen.1 | 2020/01/21 00:02:29 Received event stop for container 274d6e739fd8
dockergen.1 | 2020/01/21 00:02:29 Generated '/etc/nginx/conf.d/default.conf' from 1 containers
dockergen.1 | 2020/01/21 00:02:30 Contents of /etc/nginx/conf.d/default.conf did not change. Skipping notification 'nginx -s reload'
dockergen.1 | 2020/01/21 00:02:33 Received event start for container d661d4bff1f3
dockergen.1 | 2020/01/21 00:02:33 Generated '/etc/nginx/conf.d/default.conf' from 2 containers
dockergen.1 | 2020/01/21 00:02:33 Running 'nginx -s reload'

running docker logs private_package_name gives me nothing.

Is there something I am doing wrong here or is this some sort of a bug? Help would me much appreciated.

abnormal

upstream server temporarily disabled while connecting to upstream

no live upstreams while connecting to upstream

Max_fails and fail_timeout

Max_fails defaults to 1 and 1,fail_timeout defaults to 10 seconds.

Nginx can set the number of failed attempts and failure time of nodes by setting max _ failures (maximum number of failed attempts) and fail_timeout (failure time, after reaching the maximum number of failed attempts, the nodes are set to fail within the time range of fail_timeout, and the nodes do not recover within this time unless all nodes fail) . When the maximum number of attempts is exceeded or the failure time does not exceed the configured failure time, nginx will set the node state to a failure state, and nginx will not connect the backend until the failure time is exceeded or all nodes fail, and then the node is reset to valid and re-detected.

upstream backend {
    server backend1.example.com weight=5;
    server 127.0.0.1:8080       max_fails=3 fail_timeout=30s;
    server unix:/tmp/backend3;

    server backup1.example.com  backup;
}

Fail criteria

such as

connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: , request: "POST /demo HTTP/1.1", subrequest: "/capture/getstatus", upstream: "http://192.168.99.100:8080/api/demo/

such as

upstream timed out (110: Connection timed out) while reading response header from upstream

Nginx judges the failed node status by default based on the connect refuse and time out status, and does not judge failure based on HTTP error status. As long as HTTP can return status indicating that the node can still connect normally, Nginx judges whether it is still alive. Unless proxy_next_upstream instruction is added to set 404, 502, 503, 504, 500, time out and other errors to be transferred to standby machine for processing, fails will be accumulated during next_upstream. If standby machine processing is still wrong, error information will be directly returned (but 404 will not record the number of errors. If the error state is not configured or recorded), overview, nginx records the number of errors only in the six states of timeout, connect refuse, 502, 500, 503, 504. timeout and connect refuse are always recorded error states. However, nginx will only record these four HTTP errors into fails after configuring proxy_next_upstream. When fails is greater than or equal to max_fails, the node fails.

Detection mechanism

If all nodes are detected to be invalid and the standby machine is also invalid, then nginx will resume to be valid for all nodes and try to detect valid nodes again. If valid nodes are detected, the correct node contents will be returned. If all the nodes are still wrong, the detection will continue. If there is no correct information, the default return status for node failure is 502, but the next time the node is visited, the correct node will continue to be detected until the correct one is found.

Laboratory log

upstream test_server{
        server 192.168.99.100:80801;
        server 192.168.99.100:80802;
        server 192.168.99.100:80803;
    }
##for capture
location /api/test/demo{
            proxy_pass http://test_server/api/demo;
}    
location /api/demo{
            default_type application/json;
            content_by_lua_file conf/lua/demo.lua;
}

lua

local cjson = require "cjson.safe"
testres = ngx.location.capture("/api/test/demo",{
    method= ngx.HTTP_POST,
    body = "arg1=xxxx&arg2=xxxxx"
})
ngx.log(ngx.ERR,"status"..testres.status)
local testbody = cjson.decode(testres.body)
ngx.log(ngx.ERR,testbody==nil)

Request 192.168.99.100:8080/api/demo , lua in it will initiate a capture, Request /api/test/demo

Request once

2017/02/09 14:48:57 [error] 5#5: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.99.1, server: , request: "POST /api/demo HTTP/1.1", subrequest: "/api/test/demo", upstream: "http://192.168.99.100:80801/api/demo", host: "192.168.99.100:8080"
2017/02/09 14:48:57 [warn] 5#5: *1 upstream server temporarily disabled while connecting to upstream, client: 192.168.99.1, server: , request: "POST /api/demo HTTP/1.1", subrequest: "/api/test/demo", upstream: "http://192.168.99.100:80801/api/demo", host: "192.168.99.100:8080"
2017/02/09 14:48:57 [error] 5#5: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.99.1, server: , request: "POST /api/demo HTTP/1.1", subrequest: "/api/test/demo", upstream: "http://192.168.99.100:80802/api/demo", host: "192.168.99.100:8080"
2017/02/09 14:48:57 [warn] 5#5: *1 upstream server temporarily disabled while connecting to upstream, client: 192.168.99.1, server: , request: "POST /api/demo HTTP/1.1", subrequest: "/api/test/demo", upstream: "http://192.168.99.100:80802/api/demo", host: "192.168.99.100:8080"
2017/02/09 14:48:57 [error] 5#5: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.99.1, server: , request: "POST /api/demo HTTP/1.1", subrequest: "/api/test/demo", upstream: "http://192.168.99.100:80803/api/demo", host: "192.168.99.100:8080"
2017/02/09 14:48:57 [warn] 5#5: *1 upstream server temporarily disabled while connecting to upstream, client: 192.168.99.1, server: , request: "POST /api/demo HTTP/1.1", subrequest: "/api/test/demo", upstream: "http://192.168.99.100:80803/api/demo", host: "192.168.99.100:8080"
2017/02/09 14:48:57 [error] 5#5: *1 [lua] demo.lua:44: status502 while sending to client, client: 192.168.99.1, server: , request: "POST /api/demo HTTP/1.1", host: "192.168.99.100:8080"

If each request for upstream fails, capture’s subrequest returns 502, and the status code returned for client depends on the lua script

Ask again

2017/02/09 15:09:34 [error] 6#6: *11 no live upstreams while connecting to upstream, client: 192.168.99.1, server: , request: "POST /api/demo HTTP/1.1", subrequest: "/api/test/demo", upstream: "http://test_server/api/demo", host: "192.168.99.100:8080"

No live upstreams while connecting to upstreams when server below the upstreams are all hung up.

doc

  • ngx_http_upstream_module

  • In-depth Analysis of health_check Mechanism in nginx

  • Original fault-tolerant mechanism of nginx upstream-Hu Zhiguang

  • An analysis of “no live upstreams while connecting to upstreams” in online nginx.

08.01.2019 21:01, Eugene Toropov пишет:
> Добрый вечер,
>
> Тогда получается ситуация, при которой часть запросов файрвол пропускает, а часть режет. При чем ночью до 9 утра не режет ничего, а вечером почти все. Как nginx определяет, что апстрим живой? Любой статус, отличный от 200?

посмотрите описание proxy_next_upstream

Директива также определяет, что считается неудачной попыткой работы с
сервером. Случаи error, timeout и invalid_header всегда считаются
неудачными попытками, даже если они не указаны в директиве. Случаи
http_500, http_502, http_503, http_504 и http_429 считаются неудачными
попытками, только если они указаны в директиве. Случаи http_403 и
http_404 никогда не считаются неудачными попытками.

и директиву server из секции описания upstream

max_fails=число
    задаёт число неудачных попыток работы с сервером, которые должны
произойти в течение времени, заданного параметром fail_timeout, чтобы
сервер считался недоступным на период времени, также заданный параметром
fail_timeout. По умолчанию число попыток устанавливается равным 1.
Нулевое значение отключает учёт попыток. Что считается неудачной
попыткой, определяется  директивами proxy_next_upstream,
fastcgi_next_upstream, uwsgi_next_upstream,scgi_next_upstream,
memcached_next_upstream и grpc_next_upstream.

если апстрим реально один, то укажите ему max_fails=0

А вообще смотрите запросы рядом с первым 502. там скорее всего гдето
случились таймауты, единственный апстрим отметился как фейл и на время
fail_timeout(10с по умолчанию) выпадает из работы.

/Алексей

_______________________________________________
nginx-ru mailing list
nginx-ru@nginx.org
http://mailman.nginx.org/mailman/listinfo/nginx-ru

In this article, we discuss the use of Nginx upstream module for HTTP and CGI (FastCGI) requests.

Using Nginx upstream module is essential for scaling application backend, but there might be a few catch-ups. One of them is related to what will happen when a server fails?
There is a proxy_next_upstream directive (or for FastCGI – fastcgi_next_upstream), which instructs the upstream module what is a fail – is it a connection error or timeout or HTTP 500 returned by the upstream server or an ordinary HTTP 404 returned by the upstream server is also a fail. So when a failure is identified by the Nginx upstream module the upstream module will look for the next upstream server to handle the request. These directives instruct Nginx upstream module what is a failure then to handle the next upstream server if available.
The default values are too conservative (and probably it is better to be like that):

proxy_next_upstream error timeout;

And available options are:

proxy_next_upstream error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | http_429 | non_idempotent | off ...;

They are the same for fastcgi_next_upstream, too.

Imagine you what to protect yourself from HTTP 500? Or even HTTP 403 and 404? It’s normal to include them in your configuration. But here is the catch-up:
What if an image is really missing (HTTP 404) on all your upstream backend servers? Or there is a syntax error in an application file (like a simple PHP file)? All your upstreams servers will return 404 or 500 (in case of application error) and all of them will be blacklisted for at least 20 seconds. Remember 404 or 500 is a failure and we need next upstream server and if all return failure for this particular request Nginx will return to the client there is a problem and will mark the server as down (unavailable for a period of time).

SO because of a single file (a problem in a single file), all the following requests will be denied with “502 Bad Gateway” or “500 Internal Server Error”, even your servers are healthy!

Just a tiny miss like a missing image could be misinterpreted as your upstream servers have problems, so they must be blocked! Even if you put a “backup” directive in the upstream server line!

The solution is to include one or more of your upstream servers with disabled failure count (fail_timeout=0s) as a backup server. So this server will be always available when all normal servers got blacklisted! And you are not going to receive any more “no live upstreams” and returning an error to your clients.
Here is a working configuration (it is the same for HTTP and FastCGI setups):

upstream backend {
     server   127.0.0.1:8000;
     server   10.10.10.10:9000 fail_timeout=20s;
     server   127.0.0.1:8000 backup fail_timeout=0s max_fails=1000;
}

And be careful what you add in proxy_next_upstream (or fastcgi_next_upstream). In general, HTTP 403 and 403 are not for this directive!

A real-world example (FastCGI)

One of our project using an Nginx with the upstream module to scale the PHP application backend began to serve only HTTP 502 to all clients! In the PHP logs, there was a rear syntax error on a single file (not in the main part of the site), but Nginx was answering to all requests, no matter of the URI with 502. What had happened? The two backend application servers had returned with 500 (because of this error) and were blacklisted for 20 seconds! And all the following requests were not served by the upstream backends because there were “no live upstreams”:

upstream backend-php {
        server   127.0.0.1:8000;
        server   178.63.22.46:9000 fail_timeout=20s;
        server   127.0.0.1:8000 backup;
}

with

fastcgi_next_upstream error timeout invalid_header http_500 http_503 http_429 non_idempotent;

Even we have a backup, it was also blacklisted. In fact, a scanner was scanning all of our PHP files and one URL returned syntax error, then all of the upstream servers were blacklisted and we experienced an effective DoS because of misconfiguration. After we changed our configuration to:

upstream backend-php {
        server   127.0.0.1:8000;
        server   10.10.10.10:9000 fail_timeout=20s;
        server   127.0.0.1:8000 backup fail_timeout=0s max_fails=1000;
}

Everything returned to normal. There was still this syntax error but did not stop all other valid URLs to be served. Of course, we fixed the broken file and stopped the scammer from scanning our site.

A real-world example 2 (HTTP)

In our proxy static cache servers in remote locations, we experienced periodically “no live upstreams” and our clients received “502 Bad Gateway” on-peak hours! The problem was we have too aggressive proxy connect, read and send timeout, but because we were serving a live TV we needed them. And on-peak if a single connection just huck-up for 5-10 seconds our upstream servers were blacklisted for 20 seconds! Using proxy_cache_lock could worsen the situation! Then we changed our configuration to have a backup upstream server, which effectively would not be blacklisted and lowered the proxy_cache_lock to be sure if a single connection failed for some reason all other might succeed in bringing the file to the cache!

proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 http_403 http_404;
proxy_connect_timeout 2s;
proxy_read_timeout 5s;
proxy_send_timeout 5s;
proxy_cache_lock on;
proxy_cache_lock_timeout 20s;
proxy_cache_lock_age 10s;

with upstream configuration:

upstream backend_http {
        server 10.10.10.10 fail_timeout=20s;
        server 10.10.10.11 backup fail_timeout=0s max_fails=1000;
        keepalive 16;
}

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • No host is compatible with the virtual machine ошибка
  • No healthy upstream ошибка что значит