Nginx upstream errors

Больше способов увидеть ошибку 504 Gateway Time out

Ошибка Gateway Timeout при получении в Windows Update генерирует код ошибки 0x80244023 или сообщение WU_E_PT_HTTP_STATUS_GATEWAY_TIMEOUT.

В программах на базе Windows, которые изначально обращаются к интернету, ошибка 504 может отображаться в небольшом диалоговом окне или окне с ошибкой HTTP_STATUS_GATEWAY_TIMEOUT и/или сообщение The request was timed out waiting for a gateway (истекло время ожидания запроса для шлюза).

Менее распространенная ошибка 504 — это Gateway Time-out: The proxy server did not receive a timely response from the upstream server (прокси-сервер не получил своевременного ответа от вышестоящего сервера), но поиск и устранение неисправностей (указанных выше) продолжается.

Start With a Thorough Application Backup

As with anything, it’s better to have played it safe at the start than to screw something up and come to regret it later on down the road. As such, it is critical that you perform a full backup of your application, database, and so forth, before attempting any fixes or changes to the system, otherwise you might find yourself with additional errors and even latent errors. Even better, if you have the capability, create a complete copy of the application onto a secondary server that isn’t “live,” or isn’t otherwise active and available to the public. This will give you a clean testing ground with which to test all potential fixes to resolve the issue, without threatening the security or sanctity of your live application.

The Problem is Server-Side

All HTTP response status codes that are in the category are considered . Unlike the we’ve looked at recently, which indicates that a server somewhere in the connection chain is down or unavailable, a simply indicates that the server is temporarily unable to handle the request, but that is is functioning as normal otherwise. Unlike gateway related response codes that may indicate issues either on the web server or another server further upstream, the code generally indicates an issue on the actual web server hosting your application.

In most cases, the web server should provide a user-friendly page indicating that the service is temporarily unavailable. Additionally, the application should send a HTTP header, which informs the user agent (client) how long it should wait to attempt the request once again. This value should either be a value indicating the timestamp the service will be available, or a numeric value indicating how many seconds from now the user agent must wait to retry.

Since the indicates that something has gone wrong within the of your application, we can largely disregard the side of things. If you’re trying to diagnose an issue with your own application, you can immediately ignore most client-side code and components, such as HTML, cascading style sheets (CSS), client-side JavaScript, and so forth. This doesn’t apply solely to web sites, either. Many smart phone apps that have a modern looking user interface are actually powered by a normal web application behind the scenes; one that is simply hidden from the user. If you’re using such an application and a occurs, the issue isn’t going to be related to the app installed on your phone or local testing device. Instead, it will be something on the server-side, which is performing most of the logic and processing behind the scenes, outside the purview of the local interface presented to the user.

Diagnosing a 503 Service Unavailable Error

As mentioned, a indicates that the server (typically the actual web server on which your application is running) is temporarily unavailable. This is usually due to the server being “down” for scheduled maintenance, or due to a heavy load of traffic that is preventing it from properly serving all incoming requests. In the case of the former, the server has not actually crashed or shut down but has, instead, set itself to a mode of service that prevents most requests from behaving as normal. Thus, attempting to access a normally-functional page now displays a , ideally doing so alongside a message about the server being down for maintenance. In this mode, the server is still up and running, but only administrators will have access to it, whereas normal public requests will be turned away until maintenance is complete.

In the other scenario where the server is rejecting the request due to overload, this usually means there is an unexpected onslaught of traffic/incoming requests. In order to maintain some semblance of normal behavior for a portion of the requests, the server has effectively throttled itself by rejecting a portion of all incoming requests and returning a . If the application/server was configured correctly, the request can usually be completed by waiting a little while and retrying a few times, hopefully enough for the traffic spike to die down and let you in.

That said, if your application is responding with codes and the server should not be performing any kind of maintenance that would explain the situation, this is an issue that many other visitors could be experiencing as well, dramatically hindering your application’s ability to service users. We’ll go over some troubleshooting tips and tricks to help you try to resolve this issue. If nothing here works, don’t forget that Google is your friend. Don’t be afraid to search for specific terms related to your issue, such as the name of your application’s CMS or web server software, along with . Chances are you’ll find others who have experienced this issue and have been given a solution.

What are Nginx Upstream Errors?

With reverse proxy, it accepts a request from the client, forwards it to Upstream server(server that can complete the request), and returns the server’s response to the client.

Nginx upstream errors arise while the proxy server receive an invalid response or no response from the origin server.

Visitors will see different variations of these errors like:

502 bad gateway
502 bad gateway nginx
502 Proxy error
504 Gateway Timeout
HTTP 504 Gateway Timeout

These messages are cryptic.

So, many webmasters look at their error log:

2018/11/01 18:15:02  1713#0: *1 upstream timed out (110: Connection timed out) while connecting to upstream, client: xx.xx.xxx.xxx, server: , request: "GET / HTTP/1.1", upstream: "http://xx.xx.xx.xx:8082/", host: "xx.xx.xx.xx"

You can see that something is messed up but not sure where to start.

That’s where you need an expert to figure it out quickly and fix it permanently.

Today, let’s discuss the various reasons for nginx upstream errors and how our Dedicated Server Administrators fix them.

Nginx Upstream Errors – Top 6 reasons and solutions

In our experience handling nginx upstream errors, we’ll see the major causes that we’ve come across.

1. High load on origin server

Heavy load spike cause services to not respond.

Hence, Nginx can’t communicate with the origin server and result in this error.

The most common reasons for load spikes are:

  • Compromised server that sends malware or spam.
  • Heavy website traffic(can be marketing, promotional etc.).
  • Brute force attacks to exploit web applications.
  • Application bugs that cause resource hogging and memory leakage.
How we fix?

Our Hosting Engineers first identify the resource that is being abused. Then we find out which service is abusing that resource.

At this point, we identify the user who owns the script or software for abusing the service.

2. Service downtime in origin server

Nginx depends on various services like apache, PHP-FPM, database services, etc. to run applications.

If any of these services crash, Nginx won’t get any data and result in errors.

How we fix?

The reasons for service failure can be traffic spikes, resource outages, DDOS attacks, disk errors and so on.

We’ll identify this reason and fix it.

If a backend service fails or doesn’t respond, we’ll kill all the dead processes and restart the service.

3. Firewall blocks a request

Firewall is the keystone of server security. If not configured properly, it can block legitimate requests or services.

By default, firewall block uncommon ports in the server.

If you have a new service(eg: Ruby) enabled in the server and it runs on a custom port, there can be chances that this port is blocked in the firewall.

Hence, Nginx can’t communicate with this service and lead to this error.

How we fix?

To fix it, we look at which port each service runs on using the command netstat.

If we find any service running on custom ports, we edit the firewall configuration to allow these custom ports.

4. Network problems

DNS issues, routing problems and ISP problems can lead to Nginx upstream errors.

If recent DNS changes were made, like changing nameservers, hosting servers, etc. it will take some time to propagate globally. The domain may be unroutable during this period.

Also, sometimes ISPs may block access to a particular site.

All these can lead to such errors.

How we fix?

We check the DNS connectivity of the domain using the command:

dig domain.com

Also, we access the domain from third-party proxy servers to identify if this error is specific to the customer.

If any DNS conflicts found, we will quickly correct it. If the issue is at ISP end, then this needs to be fixed at their end.

5. Server software timeouts

Nginx upstream errors can also occur when a webserver takes more time to complete the request.

By that time, the caching server will reaches its timeout values(timeout for the connection between proxy and upstream server).

Slow queries can lead to such problems.

How we fix?

We will fine tune the following Nginx timeout values in the Nginx configuration file.

Once the timeout values are added, need to reload nginx to save these parameters.

6. Application code bugs

If all other checks failed, it can be an error in your web application code.

Sometimes, your application code may be incompatible with the server version prompting this error to show up.

How we fix?

We will diagnose the issue by analyzing the application and web server logs.

Also, we review the software requirements of your application, re-configure the services to match the required version.

Как исправить ошибку 504 Gateway Time out

Перезагрузите веб-страницу, нажав кнопку обновление / перезагрузка, в F5 или повторив URL-адрес из адресной строки.

Несмотря на то, что 504 Gateway Timeout и ошибка 502 Bad Gateway сообщает о неподконтрольной вам ошибке, проблема может быть временной. Просто перезагрузите страницу — это быстро и легко.

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

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

Проверьте настройки прокси-сервера в своем браузере или приложении. Убедитесь, что они верны. Неправильные настройки прокси-сервера могут вызвать 504 ошибку.

Подсказка. Смотрите Proxy.org обновленный, проверенный список прокси-серверов, которые можно использовать.

Примечание. Большинство компьютеров не имеют настроек прокси-сервера, поэтому, если ваши настройки пусты, пропустите этот шаг.

Измените DNS-сервер. Возможно, ошибка 504 Gateway Timeout, которую вы видите, вызвана проблемой с DNS-сервером, который вы используете.

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

Подсказка. Если не все сетевые устройства получают ошибку HTTP 504 или 502 error Bad Gateway, но все они находятся в одной сети, изменение DNS-сервера не сработает. Если это похоже на вашу ситуацию, переходите к следующей идее.

Если изменений не произошло, обратитесь к сайту. Это единственное, что вы можете сделать. Велика вероятность, что администраторы сайта уже работают, чтобы исправить первопричину ошибки 504 Gateway Timeout.

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

Подсказка. Если начинает казаться, что сайт выдает 504 ошибку для всех, поищите в в режиме реального времени информацию о недоступности сайта. Лучший способ сделать это — найти #websitedown в . Например, если может быть недоступен, выполните поиск по тегу .

  • Обратитесь к своему интернет-провайдеру. Вероятнее всего, что после описанного выше устранения неполадок, выскакивающая 504 Gateway Timeout — это проблема, вызванная неполадками в Сети, за которую отвечает ваш провайдер.
  • Вернуться позже. На данный момент вы исчерпали все варианты, и ошибка 504 Gateway Timeout устраняется администратором сайта или интернет-провайдером.

Регулярно проверяйте сайт. Без сомнения, он снова начнет работать.

Исправление ошибки 504 Gateway Time out на вашем собственном сайте

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

Большие объемы трафика могут привести к тому, что ваш сервер будет выдавать ошибку 504. Хотя 503 или ошибка 502 Bad Gateway будет более вероятна.

В частности, в WordPress сообщение 504: Gateway Timeout иногда возникает из-за поврежденных баз данных. Установите WP-DBManager и попробуйте применить функцию «Восстановить БД», а затем «Оптимизировать БД». Посмотрите, поможет ли это.

Убедитесь, что ваш файл HTACCESS правильный. Особенно если вы только что переустановили WordPress.

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

Как можно увидеть ошибку 504 Gateway Time out

Отдельным сайтам разрешено настраивать отображение ошибки Gateway Timeout. Вот несколько распространенных способов вывода подобной ошибки:

504 Gateway Timeout
HTTP 504
504 ERROR
Gateway Timeout (504)
HTTP Error 504 - Gateway Timeout
Gateway Timeout Error

Ошибка 504 Gateway Time out появляется внутри окна браузера, как обычная веб-страница. На ней могут быть знакомые верхние и нижние колонтитулы сайта и красивое английское сообщение. Также подобная ошибка может отображаться на полностью белой странице с большой цифрой 504 вверху. Это одно и то же сообщение, независимо от того, как сайт показывает его вам.

Помните, что ошибка 504 Gateway Time out и 502 Bad Gateway nginx может появиться в любом браузере, операционной системе и на любом устройстве.

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

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

Adblock
detector