Bad gateway) about hassio-zigbee2mqtt HOT 3 CLOSED

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED Хостинг

When your website experiences a 502 Bad Gateway Error, it can be like solving a mystery. You don’t know what exactly happened or why — all you know is that something’s wrong and you need to fix it.

Table of Contents

Use MetricFire’s platform to analyze your system’s performance and troubleshoot errors. For getting more detailed information about MetricFire and how to integrate it with your system, book a demo with our team or sign up on MetricFire for the free trial.

Maintaining a server is hard.

You have to deal with all the upgrades, security patches and the occassional server errors (aka errors from hell).

One such common error in Nginx servers is “502 Bad Gateway“.

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

3 word error message – because Nginx doesn’t love you. That’s why.

The error message is cryptic.

So, many web masters roll up their sleeves and look at the error log:

Yeah, more gibberish.

You know something is messed up, because it says “failed” and “refused“.

But WHAT? You hardly have time to get a PhD in computer science.

Here’s help. We’ve listed the top 5 reasons for 502 Bad Gateway error, and how we fix them.

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

Ошибка 502 Bad Gateway возникает, когда сервер, к которому вы подключены, выступает в роли посредника, передающего информацию от другого сервера, и получает некорректный ответ. 502 — это код состояния HTTP, который использует сервер для описания ошибки.

Некорректные ответы могут поступать нескольким причинам.

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

Сообщение об ошибке 502 выглядит по-разному на каждом сайте, и ее название тоже иногда различается. Например:

  • HTTP Error 502 Bad Gateway;
  • 502 Service Temporarily Overloaded;
  • Temporary Error (502);
  • 502 Server Error: The server encountered a temporary error and could not complete your request;
  • 502 Bad Gateway Nginx.

В большинстве случаев ошибка происходит на стороне сервера, и вы никак не можете ее исправить. Тем не менее есть несколько способов.

Recommend Projects

  • React
  • Vue.js
    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
  • Typescript
    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
  • TensorFlow
    An Open Source Machine Learning Framework for Everyone
  • Django
    The Web framework for perfectionists with deadlines.
  • Laravel
    A PHP framework for web artisans
  • D3
    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript
    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
  • server
    A server is a program made to process requests and deliver data to clients.
  • Machine learning
    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

Recommend Org

  • Microsoft
    Open source projects and samples from Microsoft.
  • Google
    Google ❤️ Open Source for everyone.
  • Alibaba
    Alibaba Open Source for everyone
  • D3
    Data-Driven Documents codes.
  • Tencent
    China tencent open source team.

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

502 bad gateway — что это за ошибка? Ошибка 502 Bad Gateway может проявляться по-разному. К примеру, 502 – Service Temporarily Overloaded или HTTP Error 502 Bad Gateway.

Ошибка 502 bad gateway — что это значит?

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

Ошибка bad gateway говорит о том, что обратный прокси-сервер () для сервера источника () получает некорректный ответ от исходного веб-сервера.

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

  • . Веб-сервер может падать из-за нехватки ресурсов (например, оперативной памяти), вызываемой избытком выполняемых процессов или агрессивными действиями пользователей;
  • Частая перезагрузка веб-сервера. Такое случается при ошибках конфигурации, сбоях в модулях, любых атаках, избытке выполняемых процессов и приложений. В результате пользователь видит временную ошибку;
  • Плохой код сайта. Сайты с устаревшими приложениями или корявым кодом влияют на правильное функционирование сервера и ведут к периодическому возникновению ошибки;
  • . Прочие ошибки конфигурации сети (проблемы с DNS, маршрутизация, блокировка файерволом, используемым на сервере, проблемы у провайдера) также становятся причиной появления ошибки сервера;
  • Время ожидания серверного программного обеспечения. ошибка неизбежна при снижении скорости выполнения запросов в nginx, когда средство кэширования (например, ) уходит в таймаут. Сюда же относятся и медленные запросы.

Как исправить ошибку 502 bad gateway на веб-сервере nginx

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

Затем мы покопались в конфигурации сервера, и увидели, что там отсутствовал модуль . Именно это и вызывало падение сервера:

– это модуль Reverse proxy add forward, разработанный для серверов . Он нужен в том случае, если вы задаете фронденд-сервером и хотите получить реальный серверных запросов.

Данный модуль не работал под , поэтому мы немного его подправили. После перекомпиляции и перезагрузки Apache ошибки сегментации прекратились.

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

Вот несколько советов, как исправить ошибку 502 bad gateway:

  • Следите за тем, чтобы файлы сайта (плагины и темы) своевременно обновлялись и не устаревали;
  • Оптимизируйте и исправляйте медленные ;
  • Проводите аудит серверного программного обеспечения и вовремя обновляйте модули;
  • Избегайте проблем с маршрутизацией и отслеживайте любые перегрузки/атаки на сервер.

Подскажите, после обновления докера в synology, пошли варнинги.

Там две ссылки, перейти и следовать инструкции, возможно после этого пропадут и первые два ворнинга 🙂

St. Ranger, у меня на орандж пи пс стоит armbian (только сервер), через arnbian-config установлен hass, по нагреву где то 45 градусов, загрузка в основном 5-10 процентов на ядро, иногда на на произвольном подымается выше (непродолжительно до 100 может скакануть)

Попробуйте сборку от armbian на свою плату.

andrewjswan,У меня чтото не получилось, ругается

Logger: homeassistant.components.automation.alarm_batterySource: components/automation/__init__.py:408Integration: Автоматизация (documentation, issues)First occurred: 20:48:59 (1 occurrences)Last logged: 20:48:59

Logger: homeassistant.components.automation.alarm_batterySource: helpers/script.py:1147Integration: Автоматизация (documentation, issues)First occurred: 20:48:59 (1 occurrences)Last logged: 20:48:59

Добрый вечер коллеги, прошу просветитьИмеется управление климатикой через generic_thermostatУправление идет на ESP8266 по mqttТемпература ниже уставки, то есть на ESP ушло «ВКЛ» Так вот вопрос, как часто уходит этот «ВКЛ»?Долго не наблюдал, но если выключить реле непосредственно на ESP, то включаться с HA оно уже не хочетДело в том, что у меня раз в сутки происходит перезагрузка ESP и если это произойдет, когда там «ВКЛ», то по идее он останется «ВЫКЛ», так как «ВКЛ» больше не придет

Читайте также:  Как смотреть логи сервера

andrewjswan,В итоге не чего не выводит или так и должно быть?

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

Подскажите как сделать чтобы персона отображались на карте.Геолокация на телефоне включена.В настройках приложения/сенсоры включена геолокация(геокодированное местоположение) и 3 пункта по поиску(.В графе люди выбран гаджет отслеживания.

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

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

Отвязал кнопку от реле в Aqara Single Switch Потом благополучно переустановил Home Assistant и теперь никак не могу заново привязать выключатель.Он не реагирует на нажатия клавиши, соответственно 10 секунд удержания ни к чему не приводят.

Как его можно сбросить до заводских настроек и перевести в режим сопряжения? У меня таких 6 штук, стремно все в кирпичи превратить.

В инструкции что написано?

Написано 10 секунд подержать кнопку пока не начнет мигать. Но здесь он на нее не реагирует никак

Подскажите, в чем допущена ошибка или где поискать инфу. Я уже все что мог перерыл, не могу решить эту проблему (((

Блин, объясните че аддону надо zigbee2mqtt чтобы он снова заработал после обновления, ничерта врубить я не могу

В докере на Synology?

ialtuhov, ищите по моим сообщениям в этой теме, ответ в задержке после перезагрузки сетевого менеджера

После обновления аддона zigbee2mqtt перестал открываться интерфейс — 502: Bad Gatewayа в логе ошибка

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! READ THIS CAREFULLY

какой ему вдруг френдли нейм стал мешать черт его поймешь, может кто в курсе как исправить?

Спасибо за ответ! Если отложить вопрос о целесообразности приобретения, подскажите, пожалуйста, прокидывается ли все-таки Aqara Hub (zhwg11lm) в НА? В сети не нашел однозначного ответа.

NL090, тут вроде ответил человек. Но все таки при наличии ха не имеет смысла покупать хаб

Находил инфу про задержку, закоментил, все установилось (наверное), но страница не открывается

  • What does ‘bad gateway’ mean?
  • What are the sources of the 502 Bad Gateway error?
  • Fixing the 502 error

What does ‘bad gateway’ mean?

The 502 error is usually provided with the addition Bad Gateway or as a “502 Bad Gateway Nginx”, “502 Bad Gateway Apache”, or “502 Bad Gateway registered endpoint failed to handle the request” message. Next to the well-known 404 error (“Page not found”), the bad gateway error is one of the most common error messages received when surfing the internet. It’s delivered when the server, which is accessed via the main server, couldn’t forward the request. In this case, the first server functions only as a proxy or gateway. In principle, all queries on the internet are forwarded via gateways. That’s why this error message is often so frustrating: It’s generally not at all clear at which point in the process the request encounters the error.

If you want to access a page and instead get the status code 502, there’s a high chance that the error isn’t with you. In most cases, it can be fixed by simply reloading the page. If the problem is solved by doing that, then it means that the server was just temporarily overloaded. Since such failures can also last for a fairly long time, reloading the page again is only really worth it after 15 minutes. Still receiving the same error message? Then clear your cache and cookies, as it could be that your browser didn’t truly reload the page and instead just accessed data from your internal storage (you don’t necessarily have to delete all of your cookies. Within your browser, you can display all of the cookies and remove only those that have something to do with the corresponding website.)

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

If you load a website from the Google cache, it provides a panel to inform you of when the copy was created.

To do this, you need to open the command line of your operating system (for Windows, this is the Command Prompt, for Mac, the terminal). First, locate the file to run the browser, and then type the complete path in quotation marks in the command line. Every browser manufacturer has a different command for starting the safe mode:

  • Firefox: “C:Program FilesMozilla Firefoxirefox.exe” -safe-mode
  • Internet Explorer: “C:Program FilesInternet Exploreriexplore.exe” -extoff
  • Chrome: Google’s browser doesn’t offer a safe mode. If you instead switch to incognito, all extensions will be deactivated.

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

Check which path contains the file to start the browser

You can also use something other than your standard browser. If this is successful, then it’s recommended to uninstall and reinstall your current standard browser. If switching browsers doesn’t solve the problem with the bad gateway error, then it’s time to check your network settings. The simplest option here is to restart your modem and router. If this isn’t successful, then try to switch from Wi-Fi to LAN and use a cable connection.

Sometimes, the error isn’t with you or the website operator, but instead the “502 Bad Gateway” error is the internet provider’s fault. The cause would then be a false entry on their DNS server. To bypass the error message, enter a different DNS server into your settings. On Windows, this can be changed in your TCP/IP connection settings. For testing purposes, you can access Google’s free DNS server, for example, at 8.8.8.8 and 8.8.4.4.

If the error isn’t caused by the webmaster, there’s not much left for you to do other than wait (or use a cached version). In most cases, the error is temporary and is already being tackled by the webmaster. For smaller sites, it could also be helpful to take the initiative and contact the operator of the website. It could be that they don’t know about the disruption yet and will appreciate your heads-up.

Examine the website

If you should encounter a server failure that you can’t fix within a few minutes, then you should be sure to use your social media channels to inform the visitors of your website.

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

Index management with robots. txt files

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

What is a CDN (content delivery network)?

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

Bad Request explained

HTTP 400: Bad Request explained

Перейдите в другой браузер

Проблема, вызвавшая ошибку 502 Bad Gateway, может быть связана с браузером. Как это проверить? Просто воспользуйтесь другой программой — Google Chrome, Mozilla Firefox, Apple Safari или Microsoft Edge. Если ошибка не исчезла, значит, стоит попробовать другое решение.

We strive for 99. 999% uptime

Because our system is your system.

No Credit Card Required

Using MetricFire to monitor NGINX

Did you know you can visualize your NGINX statuses with MetricFire? MetricFire ingests time-series metrics so as long as your metrics are sent in a format Graphite can ingest, MetricFire may be a great fit for you. To integrate NGINX with MetricFire, we use a Telegraf plugin. This allows you to get the visualization into your NGINX that you need. You can see the 502 errors as well as the status of your NGINX server.

Измените DNS-сервер

Иногда ошибку 502 вызывают проблемы с DNS-сервером. Можно попробовать его изменить — это не сложно. Как правило, DNS-сервер устанавливается интернет-провайдером. Вы можете изменить его на сторонний DNS-сервер, например OpenDNS или Google DNS.

What is PHP-FPM used for?

PHP-FPM (PHP-FastCGI Process Manager) is a web request processing tool for PHP applications. PHP-FPM together with NGINX can significantly increase the performance of websites and reduce resource consumption at the same time.

PHP works as an isolated service if you are using PHP-FPM. Web requests are processed over a TCP/IP socket, NGINX only handles HTTP requests, and PHP-FPM interprets PHP code. The use of separate services is very important to improve efficiency.

Читайте также:  Увеличьте скорость веб-сайта с помощью комплексной проверки загрузки сайта

To guide you through the hassle of fixing the dreaded 502 Bad Gateway Error, let’s go over what it exactly is and its most common causes and solutions.

A 502 Bad Gateway Error is a general indicator that there’s something wrong with a website’s server communication. Since it’s just a generic error, it doesn’t actually tell you the website’s exact issue. When this happens, your website will serve an error web page to your site’s visitors, like the photo below.

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

Picture Credit: Arm Mbed OS

Fortunately, there are seven common and effective solutions for analyzing and fixing most of the causes of 502 Bad Gateway Errors.

The tactics discussed below provide general fixes for 502 Bad Gateway Errors. If you have a WordPress site, this issue may require WordPress-specific solutions.

If you are the only one experiencing connectivity issues, there are several things you can do to resolve the 502 error as a website visitor.

  • Reload the page in the browser. Often the 502 error is temporary and a simple reboot can help.
  • Clear browser cache and delete cookies. The browser can save old or corrupted files and data that can cause the 502 error.
  • Try using a different browser. There may be a problem in the specific browser you are using, and the error will not occur in another browser.
  • Restart your computer and network equipment. Perhaps this is the problem and after a reboot, the error will disappear.
  • Change your DNS server. Changing the DNS server may resolve the 502 error. You can choose Open DNS or Google DNS servers.

As developer

  • Check if your server is available.
  • Check the firewall logs for unusual crashes.

Проверьте, работает ли сайт у других пользователей

Если вы не смогли получить доступ к сайту (по любой причине), можно проверить, столкнулись ли с такой проблемой другие люди. Для этого есть множество инструментов, например isitdownrightnow.com и downforeveryoneorjustme.com. Оба работают примерно одинаково: вводите адрес сайта, который нужно проверить, и получаете небольшой отчет.

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

Перезапустите устройства

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

Bad gateway) about hassio-zigbee2mqtt
 HOT 3
 CLOSED

Чтобы это исправить, можно удалить кэш и файлы cookie и снова попытаться запустить сайт.

Incorrect service configuration

Your Nginx server and the backend services relies on many sub-systems to work properly.

This includes DNS resolution, Apache processes, PHP services, DB server, etc.

If even one of these services have a wrong config entry, that service will fail to respond, and Nginx will show “502 bad gateway” error.

Some configuration issues that we’ve seen are:

  • DNS resolver misconfigured in Nginx causing domain lookups to fail.
  • DB login details set incorrectly after a recent migration, restore or upgrade.
  • Apache firewall settings (mod_security) syntax error causing Apache to crash.
  • Incorrect memory or file limits set for PHP applications.
  • Capacity limits (like no: of connections per IP) set too restrictively causing legit visits to fail.
  • ..and more

There is no easy way to find out a configuration error.

You really need to scan the error log and pay attention to what the error says.

For eg. this error here says the PHP application reached the maximum limit of processes (defined by pm.max_children setting) allowed.

As a quick aside, here’s how we prevent server errors related to config issues.

Configuration errors are generally caused by stale server settings that’s not adjusted for new traffic or site upgrades.

During this audit, we detect possible performance bottlenecks, security loopholes and hardware issues.

This helps us to proactively resolve potential issues, rather than reacting to a downtime once an error has happened.

Web application bugs

A rare case for “502 Bad Gateway” error is application code error.

If your web server logs show a scary looing error like this, it is possible that our application code is incompatible with the server version.

You’ll need to inspect the software requirements of your application, and re-configure the services to match the required versions.

What does NGINX 502 Bad Gateway mean?

502 Bad Gateway means that the server you are accessing receives an error from another server. This happens when one server acts as a proxy to receive information from another server. When connecting to another server, it returns an error. NGINX returns error 502 if it cannot connect to PHP-FPM or PHP-FPM is not responding.

There are different names for the 502 error that you can see on different sites. For example:

  • HTTP Error 502 — Bad Gateway.
  • 502 Service Temporarily Overloaded.
  • Temporary Error (502).
  • 502 Bad Gateway NGINX.
  • 502 Bad Gateway.
  • 502 Proxy Error.

Also, the appearance of the page that displays the 502 error can be customized on different sites in the same way as it is done for the 404 not found error. There are different causes of error 502. Below we will look at the main ones, as well as possible ways to fix this error.

In Summary

502 Bad Gateway in Nginx commonly occurs when Nginx runs as a reverse proxy, and is unable to connect to backend services. This can be due to service crashes, network errors, configuration issues, and more. Today we’ve seen the top 5 causes for this error, and how to fix it.

Обновите страницу

Ошибка 502 часто бывает временной, поэтому достаточно просто обновить страницу. В большинстве браузеров сделать это можно с помощью клавиш Ctrl+R (Windows) или Cmd+R (Mac), а также с помощью кнопки «‎Обновить»‎, расположенной в адресной строке. Этот способ не всегда решает проблему, но попытка займет всего пару секунд.

High server load

The second most common reason for “502 bad gateway” in Nginx is high load average in backend servers.

Load spikes cause services to not respond.

We’ve seen these reasons for load spikes:

  • Sudden spike in website traffic (can be seasonal or marketing / promotional).
  • Brute force attacks that’s designed to exploit web apps.
  • Application bugs that cause memory leaks or resource hogging.

To troubleshoot a high load issue, first we figure out which resource is being abused (I/O, Memory, CPU or Net).

Service port blocked in firewall

For instance, in Linux servers that run Plesk automation suite, Nginx runs on port 80, and Apache runs on port 7080.

Result? 502 Bad Gateway error.

Such issues often happens when a new service is enabled (eg. caching server, Ruby, etc.) in the backend, or during a migration, or after a server upgrade.

To fix it, we look at what port each service runs on using a command like this:

# netstat -lpn tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      19785/nginx tcp6       0      0 :::80                   :::*                    LISTEN      19785/nginx

and if we find any service running in non-standard ports, we either change the service configuration to change it to a standard port, or edit firewall config to allow the non-standard port.

Possible reasons for 502 Bad Gateway

Let’s take a look at some of the possible reasons for the 502 Bad Gateway.

Читайте также:  Antimalware Service Executable как отключить Win 10

NGINX is not running

systemctl status nginx

If in the response you see that the status is inactive (dead), then you need to start NGINX.

PHP-FPM is not running

If the server takes too long to respond, then a 502 error can be caused by a PHP-FPM timeout. In this case, PHP-FPM closes the connection even before the response is sent, and NGINX returns a 502 error. To fix this problem, you can increase the PHP-FPM timeout, or you will have to research your application and figure out why it is not responding for too long.

Firewall blocks requests

The domain name is not resolved to the specified IP address or all IP addresses. In this case, you need to change the DNS server and wait until the changes are propagated and become active globally.

Server is unavailable

The original server is down or there is no connection to this server.

Monitoring your system metrics with Hosted Graphite by MetricFire

To identify bottlenecks and troubleshoot errors such as error 502, it is useful to monitor the metrics of your system and the technologies you are using in your application. MetricFire has an open-source platform that provides you with the tools to monitor and analyze your system’s metrics. Grafana is a web-based analytics and data visualization application. It allows you to create various customizable can include diagrams, graphs, and notifications. You can easily monitor your Nginx instance using MetricFire.

Let’s take a look at some of the main features of Grafana:

  • Dashboard templates. You can design your dashboard in templates as if you were writing code.  With templates, you can use the same design in different environments.
  • Annotations. You can create logs and comments on your chart manually or automatically.
  • Custom Plugins. Grafana can install external plug-ins that allow you to expand its basic functionality.
  • SQL support. With SQL support, you can easily pull data from a variety of data sources.

Graphite is a tool for collecting, storing, and processing metrics. You can use Graphite as a data source for Grafana. Grafana comes with an advanced Graphite query editor that allows you to write various queries, add functions, change function parameters, accept complex nested queries using query links, and much more.

Graphite and Grafana let you track your system performance in real time. MetricFire offers hosting services for both tools, allowing you to focus on your system’s performance and monitor its metrics in your browser.

  • Reload the page.
  • Look for server connectivity issues.
  • Check for any DNS changes.
  • Sift through your logs.
  • Fix faulty firewall configurations.
  • Comb through your website’s code to find bugs.
  • Contact your host.

Reload the page.

Sometimes server connectivity issues are resolved relatively quickly. Before you dive deep into what’s causing the problem, take steps to ensure that this is actually a major error and not just a blip.

Wait a minute or two. Then reload the page. If the page loads with no error, this might’ve been a temporary connection problem.

If the page is still giving you an error, clear your browser cache and then try refreshing it once more.

If that doesn’t work, move on to investigating the error.

Look for server connectivity issues.

Most websites live on multiple servers or third-party hosting providers. If your server is down for maintenance or any other reason, your website could serve visitors a 502 Bad Gateway Error page.

The only way to troubleshoot this issue is to wait for your server to finish maintenance or fix the problem causing the error.

If you don’t want to contact your hosting service, one quick way to make this determination could involve running a ping test to see if messages are reaching your IP.

Check for any DNS changes.

If you’ve recently changed host servers or moved your website to a different IP address, it’ll make changes to your website’s DNS server. This could cause your website to serve its visitors a 502 Bad Gateway Error page.

Your website won’t be up and running until these DNS changes take full effect, which can take a few hours.

Sift through your logs.

Server logs will provide details about your server’s health and status. Sift through them to uncover and respond to any alarming information.

Fix faulty firewall configurations.

Your firewall is your website’s gatekeeper, protecting your site from malicious visitors or distributed denial-of-service (DDoS) attacks.

Sometimes, a faulty firewall configuration will cause your firewall to deem requests from a content delivery network as an attack on your server and reject them, resulting in a 502 Bad Gateway Error. Check your firewall configuration to pinpoint and fix the issue.

Comb through your website’s code to find bugs.

If there’s a mistake in your website’s code, your server might not be able to correctly answer requests from a content delivery network. Comb through your code to find bugs or copy your code into a development machine.

It’ll perform a thorough debug process that will simulate the situation that your 502 Bad Gateway Error occurred in and allow you to see the exact moment where things went wrong.

Contact your host.

If you can’t figure out the problem on your own, or if you think your host company is the culprit, give them a call. They may be able to look deeper into what’s going on and shed some light on the situation.

If the issue is on their end, they might be able to easily fix it. If the problem is something related to your website specifically, they might also be able to walk you through the solution.

Проверьте плагины и расширения

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

Key Takeaways

  • NGINX Error 502 Bad Gateway is an error message that indicates the server is receiving an error from another server and cannot connect to PHP-FPM or PHP-FPM is not responding.
  • The use of PHP-FPM with NGINX can improve the performance of websites and reduce resource consumption.
  • To solve the error, website visitors can reload the page, clear the browser cache and delete cookies, try using a different browser, or restart the router.

Backend service failed

Nginx depends on backend services like PHP-FPM, database services and cache servers to run web applications.

So, if any of these services crash or freeze, Nginx won’t get any data from them, resulting in “502 Bad gateway” error.

Some services that we’ve seen to fail are:

  • PHP
  • Apache
  • Cache
  • Database

The reasons for service failure can range from traffic spikes and resource limits to disk errors and DDoS attacks.

If you suspect a backend service is unresponsive or failed, you can try killing all unresponsive processes and restarting the service.

For instance, here’s one way we kill defunct PHP-FPM processes and restart services.

: Do not use these commands if you are not sure how it works.

If the service restart didn’t work, you may need to get someone to take a closer look at the server health.

Conclusion

In this article, we looked at what error 502 means, what are the possible reasons for its appearance, and options for fixing it. We also figured out that to eliminate errors in your system, it is important to use monitoring tools such as hosted Graphite and Grafana offered by MetricFire.

Оцените статью
Хостинги