Request failed with status code 502
Request failed with status code 502
Что такое Ошибка 502
25 октября 2017 Опубликовано в разделах: Азбука терминов. 38776
Представьте, что вы хотите попасть в известный ночной клуб. И все хотят. Фейс-контроль пропустил туда первых 50 человек из очереди. А остальным приходится ждать, когда из клуба не выйдет хотя бы один человек. Иначе бармены просто не будут справляться с таким количеством заказов, да и сохранять порядок будет намного сложнее.
Точно то же происходит на веб-сервере, если он, по каким-либо причинам, не может обслуживать все поступающие к нему запросы, включаются внутренняя защита, запрещающая пускать новых пользователей до тех пор, пока сервер не освободится.
Что означает ошибка 502
На любом сервере есть максимальное число возможных подключений. Иногда превышение этого уровня становится причиной возникновения ошибки.
Одновременно зашло слишком много пользователей
Известный конфуз “удачной” рекламной кампании заключается в том, что созданный информационный пиар привлекает посетителей настолько активно, что сайт падает под полученной нагрузкой.
Также, превышение лимита подключений может быть одним из признаков DDos-атаки хакеров, для намеренного отключения вашего портала.
Возникли проблемы на хостинге
Если вы пользуетесь услугами обычного хостера, может возникать оверселлинг, при котором запросы, приходящие на “соседствующие” сайты положат и Ваш сайт вместе с ними.
Будет полезно уточнить у администрации хостинга, что за ошибка 502 bad gateway возникла на сайте, и не причастны ли к этому ваши “веб-соседи”
Плохо настроен сервер
Возможно, перед появлением ошибки шлюза 502 Вы выполняли обновление сайта, которое повлекло за собой проблемы несовместимости отдельных утилит или аппаратной части с программной.
Проблемы подключаемых модулей
Если ошибка сервера 502 возникает лишь при обращении к скриптам определённого расширения, например PHP, возможно причина состоит в неправильной работе именно этого модуля сервера.
Как исправить ошибку 502 BAD GATEWAY
Пути исправления кода ошибки 502 Bad Gateway довольно различны и состоят в верной диагностике причин, вызвавших неполадки. Основные советы следующие.
– Только качественный трафик из Яндекса и Google
– Понятная отчетность о работе и о планах работ
– Полная прозрачность работ
Ошибка 502: что это значит и как исправить?
Ошибка 502 Bad Gateway: что это значит?
Разберём, откуда появляется ошибка 502: Bad Gateway, что это значит и почему не стоит её бояться. Начнём с расшифровки: в переводе с английского название ошибки переводится как «неверный шлюз». У этой ошибки может быть несколько причин, разберём их по порядку.
Во-первых, эта ошибка может означать сбои хостинга, на котором расположен сайт. Это может происходить из-за перезагрузки сетевого оборудования, слишком большой нагрузки на сервер. В любом случае, зная, что такое https и используя сайты с таким типом соединения, все личные данные остаются в безопасности.
Во-вторых, ошибка 502 может свидетельствовать об ошибках в работе DNS серверов. В-третьих, неправильно работающий прокси-сервер, соединяющий компьютер пользователя и целевой сервер тоже приводит к появлению 502 ошибки. Что эта ошибка означает мы разобрались, теперь рассмотрим, что с ней делать.
Ошибка 502: что делать?
Если вдруг всплывёт ошибка 502, «Что делать?» будет Вашим первым вопросом. Есть несколько способов исправить эту ошибку. Для того, чтобы уточнить, в чём может быть проблема, зайдите на любой сайт, который точно откроется. Самый простой – главная страница любой поисковой системы. Если ошибка не пропадёт – проблема не в конкретном сайте, а в соединении с серверами.
Если не работает отдельно взятый сайт –можно попробовать почистить cookie или просто подождать. Если Вы очистили файлы, подождали, но ничего не изменилось – проблема в провайдере или с серверами. Иногда такое бывает при использовании htaccess: что это такое мы разбирали до этого.
Если ошибка 502 всплыла на рабочем компьютере, стоит сразу же обратиться к системному администратору. Так как в большинстве случаев от пользователей ничего не зависит, стоит просто подождать. Через некоторое время владельца сервера устранят проблему, и сайт заработает как надо.
В некоторых случаях, ошибку 502 вызывают DDoS-атаки. Это происходит, когда на сервер, рассчитанный на несколько тысяч запросов в секунду, с помощью ботов отправляют в разы больше. Информация о том, как настроить кросспостинг, и при этом не нарушить работу сайта тоже очень важна и полезна.
Что за ошибка 502 bad gateway nginx?
Есть ещё один вопрос: что за ошибка 502 bad gateway nginx и о чём она сигнализирует. Начнём с того, что запросы от клиентов перед попаданием на сервер сайта проходят через шлюз. В большинстве случаев перед основным расположением сайта идёт веб-сервер nginx.
В этом случае он будет играть роль шлюза и передавать информацию. Если появляется 502 ошибка, значит запрос прошёл через nginx, попал на основной сервер, который не смог его обработать. Тут же пользователю отправляется отчёт об ошибке. Многие владельцы сайтов знают, как включить обновление контента, но при этом не задумываются о возможной нагрузке на сервер.
Для того, чтобы сайт корректно работал, необходима помощь специалистов. Например, веб-разработчики могут отслеживать перегрузки серверов и атаки на него. В некоторых случаях даже желательно отключить мониторинг посетителя, так как это создаёт дополнительную нагрузку.
Как видим, с ошибкой 502 могут бороться и пользователи, и специалисты сайта. Регулярная оптимизация ресурса положительно скажется на его работе и доступности. Некоторые аспекты этой работы освещены в курсе обучения SEO-оптимизации для новичков в маркетинге.
Ошибка 502 при открытии сайта что делать?
Мы уже частично затронули тему: ошибка 502 при открытии сайта что делать пользователю. Один из способов – почистить куки-файлы. Разберём, как это можно сделать и что для этого потребуется. Не стоит переживать, так как с этой проблемой справиться любой человек, а мы приведём подробную схему.
Для этого достаточно зайти в браузер, которым пользуетесь, и выбрать пункт «Настройки». Найдите функцию «Очистить историю посещений» и выберите удаление cookie-файлов за нужный промежуток времени. Эти файлы запоминают информацию о нас. Например, что нас интересовали CRM системы для малого бизнеса или другие запросы.
Всё это представлено в виде маленьких файлов, сохраняющихся на компьютере. Их регулярное удаление благотворно повлияет на работу компьютера и соединения с серверами сайтов. Так же удалить куки с нескольких браузеров сразу можно с помощью специальных программ.
Самой простой и популярной является CCleaner, последовательность действий точно такая же, как и при очищении браузера. Выберите пункты, которые нужно удалить и нажмите специальную кнопку. Для владельцев ресурсов, особенно использующих продвижение сайтов веб-студией так же следует своевременно очищать кеш.
Что за ошибка 502 в приложении?
Несомненно, стоит разобрать, что за ошибка 502 в приложении, откуда он берётся и как её устранить. Разницы в причинах появления ошибок сайтов и приложений нет. Стоит помнить, что это не проблемы с телефоном, а с интернетом или VPN соединением.
Для устранения ошибки проверьте корректность передачи данных и подождите, возможно ошибка пройдёт сама собой. Если есть ошибки работы интернета, стоит обратиться к провайдеру. Для них актуален вопрос как привлечь рефералов, поэтому к Вам отнесутся максимально внимательно и помогут решить проблему.
В заключении стоит отметить, что от появления ошибки 502 Bad Gateway никто не застрахован. Мы привели несколько способов решения проблемы. Регулярно очищая кеш и cookie-файлы, и владельцы сервера, и пользователи сведут появление страниц с ошибкой 502 к минимуму.
Error 502 Bad Gateway: Where’s the problem?
Everything doesn’t always run smoothly when surfing the net. Now and again, you’ll visit a website and instead be greeted by an HTTP status code. Something went wrong! If you run up against a 500 code as an internet user, then in most cases the problem is not with you or your internet connection — it’s far more likely that it’s the website’s server instead. With a 502 error, though, it can occasionally happen that something is wrong with your settings — especially if you’re suddenly receiving the annoying status code regardless of which sites you’re trying to access. This article gives you tips on how to suss out the source of the error and what you can do as a user to once again view the content of the website. Or are you the operator of an affected website? We’ll tell you how to check for that error too.
What does ‘bad gateway’ mean?
The internet protocol HTTP generally provides status codes in response to queries. The most common code is probably number 200: OK. Everything has worked as it should. This status isn’t usually shown to users, though. Instead, visitors simply see the requested website content. On the flip side are the error messages: While 400 codes imply that the error lies on the client side, 500 to 511 codes mean that the negative result is the server’s fault. The status codes also indicate where the error occurred — at least to users who know what the individual codes 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.
What are the sources of the 502 Bad Gateway error?
In most cases, the bad gateway error occurs on the server side and can’t be fixed by the internet user. But it’s also possible that the browser being used has registered a 502 error where really none exists. It’s also possible that you’re disconnected from your network. The following reasons could explain why the infamous HTTP code is displayed:
Fixing the 502 error
Internet users, as well as webmasters, have the ability to respond to a bad gateway situation. In many cases, just waiting for a little while is enough. Often, the error occurs outside of your sphere of influence and is solved by the internet provider (ISP) or the hosting provider of the web server without any intervention on your part. But sometimes the error is on your side, so you should know where to begin to search for the cause.
As an internet user: Fix 502 or bypass it
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.)
If the error is actually on the server side but you still want to access the content right away, there are also other ways to bypass the error message. This relies on the Google cache. Google saves websites for a time on its own servers and so can display an earlier version of the respective website. To load the cache page of the search engine, enter cache: in the search field and then the URL that you would like to visit (for example, cache:https://facebook.com). You should be aware, though, that you’re viewing an outdated version of the site. If you need to go back through the site’s history to find a working version, then the Wayback machine — from the nonprofit internet archive — can help. Various versions from the past years are stored here.
If you load a website from the Google cache, it provides a panel to inform you of when the copy was created.
The error could also be in your system — even if the status code indicates something else. To check whether the error stems from other users or you, you can, for example, use the web service Down for everyone or just me?. Of course, if you can’t access any websites without the “Bad Gateway” message, then it’s obvious that the error has something to do with your computer, browser, or firewall. If the error is actually only occurring for you, then check the functionality of your browser. The first step should be restarting the browser. If this doesn’t work, then start your browser in safe mode. In safe mode, the browser deactivates any installed plugins. This allows you to check if a browser extension is the source of the error message.
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:
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.
As a webmaster: Examine the website
A visitor to your website has shared with you that they’re seeing the error message 502 when they try to access your website. What does that mean for you? Just as for the surfing visitor, it’s not always clear to the webmaster at first glance where the error lies. First, you need to check whether your website is still accessible in general. If your server is truly failing, you should contact your hosting provider. Maybe they already know about the error and their IT team is working on a solution. You should also check the log files of your server for error messages. PHP programming in particular can often be the source of errors, so definitely check if your error source is either there or in your database. If necessary, you could use an old backup to quickly remedy the failure.
Oftentimes, the error only occurs because the server was temporarily overloaded or took too long to provide a response to the upstream server. If such overloads start occurring more frequently, you should contact your hosting provider. Together, you can achieve a better configuration for your webserver so that it doesn’t fall to its knees at peak times. But in some cases, it’s the communication between the different webservers that isn’t running smoothly. Then you should check whether your firewall is correctly set up and make sure that it’s not blocking any legitimate queries. Another source of error could be that the name resolution isn’t functioning properly. Check your name server settings with your hosting provider (for IONOS users, this takes place via the customer login. There you need to select the appropriate domain and switch to DNS settings).
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.
Устранение ошибок HTTP «502 — недопустимый шлюз» и «503 — служба недоступна» в Службе приложений Azure
«502 — недопустимый шлюз» и «503 — служба недоступна» — распространенные ошибки, возникающие при работе приложения, размещенного в Службе приложений Azure. Эта статья поможет вам устранить эти ошибки.
Если вам потребуется дополнительная помощь по любому из вопросов, рассматриваемых в статье, вы можете обратиться к экспертам по Azure на форумах MSDN Azure и Stack Overflow. Кроме того, можно зарегистрировать обращение в службу поддержки Azure. Перейдите на сайт службы поддержки Azure и щелкните Поддержка.
Симптом
При открытии приложения браузер возвращает ошибку HTTP «502 — недопустимый шлюз» или HTTP «503 — служба недоступна».
Причина
Эта проблема часто связана с проблемами на уровне приложения, например:
Действия по устранению ошибок «502 — недопустимый шлюз» и «503 — служба недоступна»
Процесс устранения неполадок можно разделить на три последовательных задачи.
Служба приложений содержит несколько параметров для каждого из этих этапов.
1. Наблюдение за поведением приложения
Мониторинг работоспособности службы
Microsoft Azure информирует о каждом случае прерывания работы или снижения производительности службы. Можно следить за работоспособностью службы на портале Azure. Дополнительные сведения см. в статье Получение информации о работоспособности службы.
Отслеживание работы приложения
Этот инструмент позволяет определить наличие проблем с приложением. В колонке вашего приложения щелкните на плитку Запросы и ошибки. Колонка Метрика содержит все метрики, которые вы можете добавить.
Некоторые из этих метрик помогут вам отслеживать работу приложения, например,
Дополнительные сведения см. в разделе:
2. Сбор данных
Использование средства диагностики
Служба приложений не требует никакой настройки и предоставляет вам интеллектуальный и интерактивный интерфейс для устранения неполадок в приложении. Если возникнут проблемы с приложением, средство диагностики предоставит сведения об ошибках, которые помогут быстрее найти нужную информацию для поиска и устранения этих проблем.
Чтобы открыть диагностику службы приложений, перейдите на портале Azure к приложению службы приложений или к среде службы приложений. На панели навигации слева щелкните Диагностика и решение проблем.
Использование консоли отладки Kudu
Служба приложений оснащена консолью отладки, с помощью которой вы можете получать сведения о среде, используя функции отладки, изучения, передачи файлов и конечных точек JSON. Она называется консоль Kudu или панель SCM приложения.
Вот некоторые возможности консоли Kudu:
У консоли Kudu есть еще одна очень полезная функция. Если приложение создает обрабатываемые исключения, с помощью консоли Kudu и средства SysInternals Procdump вы можете получать дампы памяти. Эти дампы памяти представляют собой снимок процессов и могут помочь в устранении сложных проблем в приложении.
Дополнительные сведения о возможностях консоли Kudu см. в статье Azure Websites online tools you should know about (Интерактивные инструменты веб-сайтов Azure, о которых вам нужно знать).
3. Устранение проблемы
Масштабирование приложения
В службе приложений Azure вы можете изменять масштаб выполнения приложения, чтобы увеличить его производительность и пропускную способность. Масштабирование приложения предполагает два связанных действия: изменение ценовой категории для используемого плана службы приложений на более высокую с последующей настройкой некоторых параметров.
Дополнительные сведения о масштабировании см. в статье Увеличение масштаба приложения в Azure.
Кроме того, вы можете запустить более одного экземпляра приложения. Это не только увеличит возможности обработки, но и повысит устойчивость приложения к сбоям. Если прекратит работу один экземпляр приложения, другой экземпляр продолжит обрабатывать запросы.
Вы можете выбрать ручной или автоматический режим масштабирования.
Использование функции AutoHeal
Перезапуск приложения
Обычно это самый простой способ восстановления после проблемы, которая возникла один раз. Остановить или перезапустить приложение можно с помощью колонки вашего приложения на портале Azure.
Вы также можете управлять приложением с помощью Azure PowerShell. Дополнительные сведения см. в статье Использование Azure PowerShell с диспетчером ресурсов Azure.
Что такое ошибка 502 Bad Gateway и как ее исправить
Запрос от пользователя к файлам сайта последовательно проходит через несколько условных «шлюзов»: браузер, DNS-кэш и DNS-серверы, CDN-, веб-серверы и т. д. Ошибка 502 Bad Gateway выдается, когда одно из звеньев этой цепи работает некорректно или не работает вообще.
Чаще всего причина — в перегруженности сервера, на котором расположен сайт. Ему не хватает мощностей, чтобы обработать запросы. Такое может произойти из-за:
Ошибка 502 Bad Gateway может быть связана с некорректной работой PHP-скриптов и плагинов. Иногда проблема возникает в работе MySQL или службы Memcached.
Действия администратора сайта при ошибке 502
Ошибка 502 Bad Gateway сравнительно неплохо диагностируется: есть множество способов найти и устранить ее причину. Если сайт расположен на виртуальном хостинге, инструментов не так много (журнал ошибок, проверка плагинов). Лучше всего обратиться к хостинг-провайдеру.
У владельцев VPS/VDS и «дедиков» возможностей для диагностики больше.
Посмотрите информацию на странице ошибки
Иногда там могут быть указаны полезные сведения — на каком этапе произошел сбой.
К примеру, если в ошибке есть сообщение о cloudflare-nginx, то обрыв соединения произошел на серверах Cloudflare — популярного поставщика CDN-услуг. Обратитесь в их техподдержку.
Проверьте доступность проблемной страницы с помощью сервисов
Чтобы убедиться, что проблема не локальная, проверьте, виден ли ваш сайт другим пользователям. Для этого можно использовать специальные сервисы, например, https://2ip.ru/site-availability/. Если проверка показывает, что сайт действительно недоступен, переходите к следующим шагам.
Проверьте журнал ошибок и логи сервера
Вы можете посмотреть журнал ошибок вашей CMS. В WordPress журнал расположен в папке wp-content, файл называется debug.log. Если такого файла нет или он пустой — нужно включить запись логов в конфигурационном файле wp-config.php.
Если у вас VPS/VDS или выделенный сервер, дополнительно посмотрите логи сервера. По ним можно определить:
Исходя из результатов проверки можно предпринять действия для решения проблемы:
Проверка плагинов CMS
Ошибку с кодом 502 Bad Gateway могут вызывать некорректно работающие плагины WordPress. Например, плагины кеширования.
Чтобы проверить, в этом ли причина, найдите папку с плагинами и переименуйте ее (можно дать любое имя). CMS перестанет использовать плагины. Если ошибка после этого исчезнет — проблема в них. Включите плагины снова (верните папке прежнее имя) и отключайте последовательно каждый, чтобы определить «виновника».
Проверка командой top
Исправление ошибки 502 на виртуальном сервере можно начать с проверки командой top (на виртуальном хостинге такая возможность чаще всего недоступна).
Проверка может выявить, что:
Действия пользователя при ошибке 502
Чаще всего причина ошибки на сервере или хостинге сайта. Но в некоторых случаях сбой происходит у пользователя. Чтобы исправить ситуацию или убедиться, что проблема не у вас, сделайте следующее:
Обратитесь в техподдержку
Если проблему не удалось решить своими силами, напишите или позвоните в техподдержку вашего хостинга. Во-первых, причины ошибки могут быть в каких-то настройках, которые доступны только им. Во-вторых, у специалистов провайдера гораздо больший опыт по части решения проблем с сервером.
При обращении обязательно укажите, что вы уже предприняли для диагностики и исправления. Это поможет быстрее установить причину.
«502 Bad Gateway»: что означает эта ошибка и как ее исправить
Что значит ошибка «502 Bad Gateway»
Ошибку «502 Bad Gateway» стоит понимать как то, что от входящего сервера был получен неверный ответ. Об это говорит и перевод на русский названия ошибки: 502 Bad Gateway – 502 Плохой Шлюз.
А сам код состояния ошибки – 502 – согласно международной классификации и Инженерному Совету Интернета (IETF), говорит о том, что сервер (выступая как прокси или шлюз), при попытке связаться с удаленным сервером, получил недопустимый ответ.
И здесь может быть не только ошибка №502, но и 501, или 511, или другой номер из этой серии. Но все они говорят о том, что запрос дошел до удаленного сервера, но что-то помешало его выполнению. А значит пользователь браузера никак не может повлиять на ситуацию – проблема на другой стороне.
Встречающиеся варианты ошибок 502 
В зависимости от вашего браузера или операционной системы ошибка сервера 502 может отображаться на экране по-разному. Так, например, вы можете встретить такие варианты:
Все они означают одно и то же, а как справится с ними мы сейчас расскажем.
Как исправить ошибку 502 Bad Gateway
Как мы уже говорили, ошибка 502 Bad Gateway возникает из-за проблем сервера. Но есть несколько вещей, которые может сделать обычный пользователь, чтобы восстановить корректное отображение сайта.
Перезагрузите страницу
Первая вещь, которую стоит делать всем пользователям в Сети при некорректной загрузке страницы, — это ее перезагрузка. Это же правило отлично подходит и для ошибки сервера 502.
Но для перезагрузки лучше использовать не специальный значок в браузере, а сочетание горячих клавиш: Ctrl + F5. Такой тип перезагрузки будет запрашивать все данные о странице, а не будет обращаться к памяти кэшированных данных в браузере.
Возможно, отсутствие ответа сервера было всего секундным, и следующая перезагрузка исправит ситуацию.
Почистите кэш
По этой же причине не лишним будет и очистить весь кэш в браузере. Это можно сделать в настройках приложения. Особенно это касается устранения ошибки 502 Bad Gateway на телефонах.
Проверьте работоспособность сайта
Чтобы наверняка быть уверенным, что проблемы с отображением сайта лежат на удаленном сервере, а не на стороне пользователя, попробуйте запустить сайт через другой браузер.
Проверить отклик сайта можно и через специализированные сервисы, например, тут.
Убедитесь в уверенном подключении к Интернету
Нестабильное подключение к Сети может быть причиной отказа в получении данных с сервера.
Проблемы с DNS
Одним из триггеров, приводящих к ошибке 502 Bad Gateway, может стать то, что DNS-сервер не отвечает.
Часто эта проблема бывает при переносе домена сайта на новый хостинг. Здесь придется только набраться терпения, так как отображение сайта будет зависеть от того как быстро обновиться каталоги IP-адресов. Так, каталоги Google обновляются в течение 24 часов, а иногда и чаще. Региональные каталоги могут обновляться и раз в неделю.
Со своей стороны, пользователь может ускорить этот процесс, прописав DNS-сервера от Google:
Также стоит попробовать очистить локальный кэш DNS. Для этого запустите строку «Выполнить» (WIN+R), введите cmd и нажмите Ок. Затем введите:
и нажмите Enter. Если на экране появилась запись об успешной очистке кэша DNS, то все прошло правильно.
Это все, что может сделать со своей стороны пользователь. Остальное уже зависит от разработчиков сайта и от сервера, на котором он размещен.
Улучшите условия использования сервера
Общие хостинги ограничивают количество направленных запросов на конкретный сайт. Делается это для того, чтобы внезапная активность на одном сайте не повлияла на других пользователей сервера и их веб-ресурсы.
Увеличиваем лимиты нагрузки на сервер. На примере хостинга beget.com
Если ваш сайт стал популярнее, а количество посетителей на нем выросло, это может привести к тому, что запросы к серверу сверх лимита будут сбрасываться. Чтобы этого не происходило, смените свой вариант тарификации хостинга. Возможно вам даже стоит попробовать услуги выделенного сервера или вообще другого провайдера хостинга.
Проверьте код сайта
Проблемы с ошибкой 502 на сайте могут возникать из-за плохого кода, который генерирует большое количество запросов к серверу от одного пользователя. Разработчики сайта должны выявит точки излишней активности, и, при необходимости, переписать код.
Если вы сами делали сайт на WordPress, то проблема, возможно, скрывается в плагинах или даже в теме, установленных на сайте. В этом случае вам нужно будет поочередно отключать их работу, чтобы понять, где закралась ошибка в коде.
Почему возникает ошибка 502 Bad Gateway Nginx
502 Bad Gateway Nginx – эта все та же ошибка ответа сервера. Она лишь указывает на то, что между браузером и сервером есть еще веб-сервер, который и дал ответ. Но по сути это ошибка относится к серверу, а не к посреднику. Веб-сервер используется как посредник не всеми сайтами, а только тогда, когда разработчик хочет снять нагрузку на сервер. Одним из примеров такого веб-сервера будет Nginx, отсюда и уточненное название ошибки.
Негативное влияние на SEO
Есть много факторов, которые влияют на позицию сайта в выдаче поисковых систем по ключевым словам. И один из них – корректная работа веб-ресурса. Особенно это стало актуально, когда в мае 2021 года Google запустил Core Web Vitals.
Конечно, если сайт был недоступен для пользователей и поисковых роботов незначительное время, то для SEO такой сбой пройдет незаметно. Однако если сайт был недоступен целый день, или еще хуже – несколько дней, то это значительно испортит рейтинг сайта в глазах поисковой системы.
Как видите, ошибка 502 Bad Gateway относится к серверу, на котором располагаются файлы сайта. Однако иногда есть способы и со стороны пользователя устранить эту проблему. Надеемся мы подробно о них рассказали, а если у вас остались вопросы – задавайте их ниже в комментариях.
Ошибка 502 Bad Gateway что значит и как ее исправить
Ошибка 502 (ERROR 502 Bad Gateway) — это сбой, который свидетельствует о получении некорректного ответа от вышестоящего по иерархии сервера. Простыми словами это получение неправильного ответа, приводящего к невозможности загрузить контент страницы.
Важно: сбой Bad Gateway может появляться как на определенной странице сайта, так и сразу на всех. Но наиболее часто встречается именно первый случай.
Чаще всего возникает по вине хостинга, DNS или прокси-сервера. Логика появления ошибки следующая: файлы публичного веб-сайта всегда располагаются на сервере. Пользовательский клиент (чаще всего, браузер) делает соответствующий запрос, чтобы получить данные из физического сервера и вывести их на пользовательском компьютере. Когда отправить файлы не получается — выводится ошибка с кодом от 500-й до 511-й.
Сам текст ошибки 502 может различаться. Часто встречаются варианты 502 Server Error, Bad Gateway, Temporary Error, HTTP 502 и другие.
Как исправить ошибку 502 вебмастеру: пошаговый алгоритм
Рассмотрим возможные причины и разберем алгоритм исправления источника ошибки.
Недостаток вычислительных ресурсов. Тарифный план хостинга
Если у вас жесткое ограничение производительности на выбранном тарифном плане хостинга, ошибка Bad Gateway может появляться при попытке открыть любую страницу сайта. Особенно часто эта причина встречается при использовании VPS на начальных тарифах.
Недостаток производительности хостинга особенно часто проявляется при аномально высокой посещаемости.
Обратите внимание на параметры total (общий объем памяти), free (свободный объем памяти в данный момент), used (использующийся объем памяти в данный момент).
Если вы видите, что свободной памяти еще много, то причину ошибки нужно искать в другом.
Увеличение лимитов FastCGI
Проект HTTP-сервера Apache, широко известный как Apache HTTPD или Apache, представляет собой HTTP-сервер с открытым исходным кодом, на котором работает большая часть веб-приложений. Apache HTTPD является кроссплатформенным и может работать в системах на базе Unix и Windows.
Обратите внимание: директива клиент-серверного протокола FastCG в конфигурационном файле обозначается как mod_fastcgi:
Глобальные изменения на сайте: обновления, установка плагинов, изменение дизайна или структуры URL
Чтобы диагностировать эту причину, необходимо проверить логи сервера. Кстати, в логах вы также сможете обнаружить и нехватку памяти сервера: такая ошибка называется OOM.
Директивы в формате combined выглядят так:
Cloudflare
Если вы настроили Cloudflare или похожее решение против хакерских атак, попробуйте отключить эту защиту. Часто Bad Gateway ошибка возникает по вине таких сервисов. То же самое можно сказать и о сторонних сетях доставки содержимого (СDN), с которыми соединен ваш сайт.
Важно: отключение вашего сайта от любых сервисов, которые перенаправляет ваш трафик на собственные сервера (например, тот же CloudFlare) произойдет не сразу, а только через 5-6 часов или даже дольше, так как должно произойти обновление записей DNS.
Конфликт плагинов, проблемы после обновления CMS
Всегда запоминайте (а лучше — записывайте) все изменения, которые вы делаете на сайте. Будь то установка плагина, добавление нового функционала или изменение дизайна страницы. Так вы сможете просто диагностировать источник появления ошибки 502 и сразу перейти к его устранению. Например — удалить конфликтующий плагин через админку используемой CMS.
Откат к исправно работающей версии сайта может стать решением Bad Gateway в ряде случаев.
Как правило, хостинги автоматически создают резервные копии сайтов и баз данных своих пользователей один раз в сутки.
Показываем на на примере хостинга Beget:
Вы можете настроить автоматическое копирование или бэкап по требованию.
Как исправить ошибку 502 пользователю: пошаговый алгоритм
Мы уже отмечали в начале, что источник Bad Gateway чаще всего находится на стороне сервера, поэтому пользователь устранить эту ошибку самостоятельно не сможет.
Но в редких случаях появление сбоя связано с проблемами, которые можно решить. Например, очисткой временных файлов сайта (поможет, если администратор вносил изменения в контент страницы и при этом на сайте настроено кэширование).
Чтобы устранить ошибку, выполните следующие действия:
Все, DNS cache успешно очищен:
Резюме: самые частые причины появления ошибки
Итак, можно вывести четыре самых распространенных сценария появления Bad Gateway на сайте:
Найдите свою причину и устраните ее, следуя нашему алгоритму.
Troubleshooting 502 Errors in ARR
by Richard Marr
Tools Used in this Troubleshooter:
This material is provided for informational purposes only. Microsoft makes no warranties, express or implied.
Figure 1 (Click image to expand)
The root cause of the error will determine the actions you should take to resolve the issue.
502.3 Timeout Errors
The error code in the screenshot above is significant because it contains the return code from WinHTTP, which is what ARR uses to proxy the request and identifies the reason for the failure.
You can decode the error code with a tool like err.exe. In this example, the error code maps to ERROR_WINHTTP_TIMEOUT. You can also find this information in the IIS logs for the associated website on the ARR controller. The following is an excerpt from the IIS log entry for the 502.3 error, with most of the fields trimmed for readability:
sc-status | sc-substatus | sc-win32-status | time-taken |
---|---|---|---|
502 | 3 | 12002 | 29889 |
The win32 status 12002 maps to the same ERROR_WINHTTP_TIMEOUT error reported in the error page.
What exactly timed-out?
We investigate this a bit further by enabling Failed Request Tracing on the IIS server. The first thing we can see in the failed request trace log is where the request was sent to in the ARR_SERVER_ROUTED event. The second item I have highlighted is what you can use to track the request on the target server, the X-ARR-LOG-ID. This will help if you are tracing the target or destination of the HTTP request:
77. | ARR_SERVER_ROUTED | RoutingReason=»LoadBalancing», Server=»192.168.0.216″, State=»Active», TotalRequests=»3″, FailedRequests=»2″, CurrentRequests=»1″, BytesSent=»648″, BytesReceived=»0″, ResponseTime=»15225″ 16:50:21.033 |
---|---|---|
78. | GENERAL_SET_REQUEST_HEADER | HeaderName=»Max-Forwards», HeaderValue=»10″, Replace=»true» 16:50:21.033 |
79. | GENERAL_SET_REQUEST_HEADER | HeaderName=»X-Forwarded-For», HeaderValue=»192.168.0.204:49247″, Replace=»true» 16:50:21.033 |
80. | GENERAL_SET_REQUEST_HEADER | HeaderName=»X-ARR-SSL», HeaderValue=»», Replace=»true» 16:50:21.033 |
81. | GENERAL_SET_REQUEST_HEADER | HeaderName=»X-ARR-ClientCert», HeaderValue=»», Replace=»true» 16:50:21.033 |
82. | GENERAL_SET_REQUEST_HEADER | HeaderName=»X-ARR-LOG-ID», HeaderValue=»dbf06c50-adb0-4141-8c04-20bc2f193a61″, Replace=»true» 16:50:21.033 |
83. | GENERAL_SET_REQUEST_HEADER | HeaderName=»Connection», HeaderValue=»», Replace=»true» 16:50:21.033 |
The following example shows how this might look on the target server’s Failed Request Tracing logs; you can validate that you have found the correct request by matching up the «X-ARR-LOG_ID» values in both traces.
185. | GENERAL_REQUEST_HEADERS Headers=»Connection: Keep-Alive Content-Length: 0 Accept: */* Accept-Encoding: gzip, deflate Accept-Language: en-US Host: test Max-Forwards: 10 User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0) X-Original-URL: /time/ X-Forwarded-For: 192.168.0.204:49247 X-ARR-LOG-ID: dbf06c50-adb0-4141-8c04-20bc2f193a61 |
---|---|
345. | GENERAL_FLUSH_RESPONSE_END BytesSent=»0″, ErrorCode=»An operation was attempted on a nonexistent network connection. (0x800704cd)» 16:51:06.240 |
In the above example, we can see that the ARR server disconnected before the HTTP response was sent. The timestamp for GENERAL_FLUSH_RESPONSE_END can be used as a rough guide to find the corresponding entry in the IIS logs on the destination server.
date | time | s-ip | cs-method | cs-uri-stem | cs-uri-query | s-port | cs-username | sc-status | sc-substatus | sc-win32-status | time-taken |
---|---|---|---|---|---|---|---|---|---|---|---|
2011-07-18 | 16:51:06 | 92.168.0.216 | GET | /time/ | — | 80 | — | 200 | 0 | 64 | 45208 |
Note that IIS on the destination server logged an HTTP 200 status code, indicating that the request completed successfully. Also note that the win32 status has changed to 64, which maps to ERROR_NETNAME_DELETED. This generally indicates that the client (ARR being the ‘client’ in this case) had disconnected before the request completed.
What happened?
Only the ARR server is reporting a timeout, so that is where we should look first.
In the IIS log entry from the ARR server, we can see that the time-taken is very close to 30 seconds, but the member server log shows that it took 45 seconds (45208 ms) to send the response. This suggests that ARR is timing the request out, and if we check the proxy timeout in the server farm’s proxy settings, we will see that it is set to 30 seconds by default.
So in this case we can clearly see that the ARR timeout was shorter than the execution of the request. Therefore, you would want to investigate whether this execution time was normal or whether you would need to look at why the request was taking longer than expected. If this execution time was expected and normal, increasing the ARR timeout should resolve the error.
Other possible reasons for ERROR_WINHTTP_TIMEOUT include:
Looking at the first two examples, ResolveTimeout and ConnectTimeout, the troubleshooting methodology outlined above would not work. This is because you would not see any traffic on the target server and therefore would not know the error code. Thus in this case of ResolveTimeout or ConnectTimeout you would want to capture a WinHTTP trace for additional insight. See the WinHTTP/WEBIO Tracing section of this troubleshooter as well as the following blogs for additional examples on troubleshooting and tracing:
502.3 Connection Termination Errors
Figure 2 (Click image to expand)
The error 0x80072efe corresponds to ERROR_INTERNET_CONNECTION_ABORTED. The request can be traced to the server that actually processed it using the same steps used earlier in this troubleshooter, with one exception; while Failed Request Tracing on the destination server shows the request was processed on the server, the associated log entry does not appear in the IIS logs. Instead, this request is logged in the HTTPERR log as follows:
The error below is another example of an invalid response from the member server:
Figure 3 (Click image to expand)
In this example, ARR started to receive data from the client but something went wrong while reading the request entity body. This results in the 0x80072f78 error code being returned. To investigate further, use Network Monitor on the member server to get a network trace of the problem. This particular error example was created by calling Response.Close() in the ASP.net page after sending part of the response and then calling Response.Flush(). If the traffic between the ARR server and the member servers is over SSL, then WinHTTP tracing on Windows Server 2008 or WebIO tracing on Windows Server 2008 R2 may provide additional information. WebIO tracing is described later in this troubleshooter.
502.4 No appropriate server could be found to route the request
The HTTP 502.4 error with an associated error code of 0x00000000 generally indicates that all the members of the farm are either offline, or otherwise unreachable.
Figure 4 (Click image to expand)
The first step is to verify that the member servers are actually online. To check this, go to the «servers» node under the farm in the IIS Manager.
Figure 5 (Click image to expand)
Servers that are offline can be brought back online by right-clicking on the server name and choosing «Add to Load Balancing». If you cannot bring the servers back online, verify the member servers are reachable from the ARR server. The «trace Messages» pane on the «servers» page may also provide some clues about the problem. If you are using Web Farm Framework (WFF) 2.0, you may receive this error if the application pool restarts. You will need to restart the Web Farm Service to recover.
WinHTTP/WebIO Tracing
Usually, Network Monitor will provide you with the information you need to identify exactly what is timing out, however there are times (such as when the traffic is SSL encrypted) that you will need to try a different approach. On Windows 7 and Windows Server 2008R2 you can enable WinHTTP tracing using the netsh tool by running the following command from an administrative command prompt:
Then, reproduce the problem. Once the problem is reproduced, stop the tracing by running the following command from the command prompt:
To analyze the log, open it in Netmon 3.4 or later. Make sure you have set up your parser profile as described here. Scroll through the trace until you find the w3wp.exe instance where ARR is running by correlating with the «UT process name» column. Right click on w3wp and choose «Add UT Process name to display filter». This will set the display filter similar to:
You can further filter the results by changing it to the following:
You will need to scroll through the output until you find the timeout error. In the example below, a request timed out because it took more than 30 seconds (ARR’s default timeout) to run.
In this next example, the content server was completely offline:
502 Ошибка шлюза
Как исправить ошибку 502 Bad Gateway
Ошибка 502 Bad Gateway – это код состояния HTTP, который означает, что один сервер в Интернете получил неверный ответ от другого сервера.
Ошибки 502 Bad Gateway полностью не зависят от вашей конкретной настройки. Это означает, что вы можете увидеть их в любом браузере, в любой операционной системе и в любом устройство.
Ошибка 502 Bad Gateway отображается в окне интернет-браузера, как и веб-страницы.
Как появляется ошибка 502 Bad Gateway
Ошибка Bad Gateway, полученная в Центре обновления Windows, генерирует код ошибки 0x80244021 или сообщение WU_E_PT_HTTP_STATUS_BAD_GATEWAY.
Причиной 502 ошибок Bad Gateway
Ошибка HTTP Error 502.1 – Bad Gateway относится к проблеме тайм-аута приложения CGI и ее лучше устранить как проблему тайм-аута 504 Gateway.
Как исправить 502 Bad Gateway
Ошибка 502 Bad Gateway часто является сетевой ошибкой между серверами в Интернете, то есть проблема не связана с вашим компьютером или подключением к Интернету.
Однако, возможно, что с вашей стороны что-то не так, вот некоторые исправления, которые стоит попробовать:
Попробуйте снова загрузить URL-адрес, нажав F5 или Ctrl + R на клавиатуре, или нажав кнопку обновления/перезагрузки.
Хотя ошибка 502 Bad Gateway обычно указывает на сетевую ошибку вне вашего контроля, она может быть чрезвычайно временной. Повторная попытка страницы часто будет успешной.
Начните новый сеанс браузера, закрыв все открытые окна браузера, а затем открыв новый. Затем попробуйте открыть веб-страницу снова.
Возможно, ошибка 502, которую вы получили, произошла из-за проблемы на вашем компьютере, возникшей когда-то во время этого использования вашего браузера. Простой перезапуск самой программы браузера может решить проблему.
Очистите кеш вашего браузера. Устаревшие или поврежденные файлы, которые хранятся в вашем браузере, могут вызывать проблемы 502 Bad Gateway.
Удаление этих кэшированных файлов и повторное использование страницы решит проблему, если это является причиной.
Удалите куки вашего браузера. По тем же причинам, которые упоминались выше для кэшированных файлов, очистка сохраненных файлов cookie может исправить ошибку 502.
Если вы не хотите удалять все свои cookie-файлы, сначала попробуйте удалить только те cookie-файлы, которые относятся к сайту, на котором появляется ошибка 502. Лучше всего удалить их все, но не помешает вначале попробовать явно применимые (ие).
Запустите браузер в безопасном режиме: Firefox, Chrome или Internet Explorer. Запускать браузер в безопасном режиме означает запускать его с настройками по умолчанию и без надстроек или расширений, включая панели инструментов.
Если ошибка 502 больше не появляется при запуске браузера в безопасном режиме, вы знаете, что причиной проблемы является расширение или настройка браузера.Верните настройки браузера по умолчанию и/или выборочно отключите расширения браузера, чтобы найти основную причину и навсегда устранить проблему.
Безопасный режим браузера по идее похож на безопасный режим в Windows, но это не одно и то же. Вам не нужно запускать Windows в безопасном режиме, чтобы запустить любой браузер в его «безопасном режиме».
Попробуйте другой браузер. Популярные браузеры включают Firefox, Chrome, Opera, Internet Explorer и Safari, среди других.
Если альтернативный браузер не выдает ошибку 502 Bad Gateway, теперь вы знаете, что источником проблемы является исходный браузер. Предполагая, что вы следовали приведенным выше советам по устранению неполадок, сейчас самое время переустановить браузер и посмотреть, исправит ли это проблему.
Загрузите обновление программного обеспечения 1 для Microsoft Forefront Threat Management Gateway (TMG) 2010 с пакетом обновления 1 (SP1), если у вас установлен MS Forefront TMG SP1 и вы получили сообщение Код ошибки: 502 Ошибка прокси-сервера. Ошибка входа в сеть. (1790) или подобное сообщение при доступе к веб-странице.
Это не распространенное решение для сообщений об ошибках 502 Proxy и применяется только в этой конкретной ситуации. Forefront TMG 2010 – это пакет программного обеспечения для бизнеса, и вы будете знать, установлен ли он у вас.
Перезагрузите компьютер. Некоторые временные проблемы с вашим компьютером и тем, как он подключается к вашей сети, могут вызывать ошибки 502, особенно если вы видите ошибку на нескольких сайтах. В этих случаях перезагрузка поможет.
Перезагрузите сетевое оборудование. Проблемы с вашим модемом, маршрутизатором, коммутаторами или другими сетевыми устройствами могут вызывать 502 Bad Gateway или другие ошибки 502. Простой перезапуск этих устройств может помочь.
Измените DNS-серверы либо на своем маршрутизаторе, либо на компьютере или устройстве. Некоторые ошибки Bad Gateway вызваны временными проблемами с DNS-серверами.
Если вы ранее не меняли их, DNS-серверы, которые вы сейчас настроили, вероятно, автоматически назначаются вашим интернет-провайдером. К счастью, для вашего использования доступен ряд других DNS-серверов. Смотрите наш список бесплатных и общедоступных DNS-серверов.
Обращение к сайту напрямую также может быть хорошей идеей. Скорее всего, предполагая, что они виноваты, администраторы веб-сайта уже работают над устранением причины ошибки 502 Bad Gateway, но не стесняйтесь сообщить им об этом.
Смотрите нашу контактную страницу веб-сайта для списка контактов для популярных веб-сайтов. Большинство веб-сайтов имеют учетные записи в социальных сетях, которые они используют для поддержки своих услуг. У некоторых даже есть телефон и контакты по электронной почте.
Если вы подозреваете, что веб-сайт закрыт для всех, особенно для популярного, проверка Twitter на предмет болтовни о сбоях часто очень полезна. Лучший способ сделать это – поискать #websitedown в Twitter, как в #cnndown или #instagramdown. Существуют и другие способы проверить, не работает ли веб-сайт, если социальные сети бесполезны.
Обратитесь к вашему интернет-провайдеру. Если ваш браузер, компьютер и сеть работают, и веб-сайт сообщает, что страница или сайт работает для них, проблема 502 Bad Gateway может быть вызвана проблемой сети, за которую отвечает ваш провайдер.
См. Как обратиться в службу технической поддержки, чтобы узнать, как поговорить с вашим провайдером об этой проблеме.
Вернуться позже. На этом этапе устранения неполадок сообщение об ошибке 502 Bad Gateway почти наверняка является проблемой либо у вашего интернет-провайдера, либо у сети веб-сайта – одна из двух сторон могла бы даже подтвердить это для вас, если бы вы связались с ними напрямую. В любом случае, вы не единственный, кто видит ошибку 502, поэтому вам нужно подождать, пока проблема не будет решена за вас.
Другие ошибки, такие как 502 Bad Gateway
Ряд других ошибок связан с ошибкой 502 Bad Gateway: 500 Внутренняя ошибка сервера, 503 Сервис недоступен и 504 Время ожидания шлюза.
Также существует ряд кодов состояния HTTP на стороне клиента, например, очень распространенная ошибка 404 Not Found, среди многих других, которые вы можете найти в этом списке ошибок кода состояния HTTP.
Что такое ошибка 502 Bad Gateway и как с ней бороться
Активные пользователи интернета нередко встречаются с разного рода ошибками, связанными с работой сервера, DNS, хостинга и так далее. Сегодня мы поговорим о 502 Bad Gateway, что это значит и как с ней бороться. Обычно оповещение об этой проблеме возникает при повторном обращении к одному и тому же ресурсу и ограничивает просмотр сайта.
502 Bad Gateway, что это значит
Дословный перевод ошибки с английского языка означает «Плохой шлюз». Таким образом, получается, что данная проблема связана с работой сервера и никак не зависит от действий пользователя.
Как правило, такую ошибку отдают ресурсы в ответ на обращение в случае, если имеются проблемы с работой прокси, DNS или хостинг-сервера. Собственно, все ошибки серии 5ХХ означают, что трудности возникли на стороне сервера. Причём чаще всего надпись на белом экране появляется именно при повторном обращении к определённому ресурсу.
Процесс, вследствие которого пользователь получает подобное оповещение следующий. Браузер отправляет на сервер запрос, как правило, по ссылке, ранее открывавшейся в обозревателе. В ответ ему приходит ошибка сервера, и как результат сообщение пользователю 502 Bad Gateway.
Причины возникновения 
Ошибка 502 Bad Gateway, что это значит стало понятно. Разберёмся какие могут быть причины для её возникновения. Несмотря на то что такая информация больше будет полезна владельцам серверов и сайтов мы углубимся в подробности.
Первой причиной появления такой ошибки становится низкая мощность сервера, к которому обращается запрос. Например, если он рассчитан на обработку 5 тысяч запросов в секунду, а ему отправляют от 7 до 10 тысяч обращений, сервер очень скоро отправить пользователям ошибку 502. Для решения проблемы в данном случае необходимо наращивать мощности сервера, это добавление памяти, которой недостаточно в текущем объёме и расширение канала. Особенно свойственно появление такой проблемы для серверов, организованных на базе домашних ПК, подобную нагрузку обычный компьютер не в состоянии выдержать, поэтому при малейшем её увеличении сервер падает.
Ещё один вариант развития событий, следствием которой становится ошибка 502 Bad Gateway — DDoS-атака на конкретный сервер сайта. Это та же разновидность перегруженности, но спровоцированная искусственным путём. Как правило, такие атаки специально заказываются конкурентами. На сервер с помощью ботов отправляется огромное количество запросов, которые он не способен обработать. Вследствие чего сервер падает, а посетитель ресурса задается вопросом, 502 Bad Gateway что это значит.
Как бороться
Как уже упоминалось выше, ошибка вызвана проблемами со стороны сервера. От пользователя мало что зависит, в связи с этим чаще всего единственным вариантом решения проблемы становится ожидание. Техническая поддержка ресурса решить проблему и доступ на сайт возобновится.
Что может предпринять пользователь 
Чтобы успокоить себя и с чистой совестью ожидать починки сервера зная, что пользователь со своей стороны сделал все возможное для устранения ошибки, нужно предпринять следующие меры.
Для тех, кто не знает, как очистить куки-файлы в своем браузере предлагаем краткую инструкцию.
Для всех остальных браузеров план действий будет примерно аналогичным. В настройках нужно найти раздел истории и очистить её вместе с куки-файлами, полученными от посещённых ресурсов.
Если ничего не помогло 
Если вы проделали все вышеперечисленные действия. Подождали некоторое время, позвонили провайдеру и убедились, что c интернетом у вас все в порядке, при этом ERROR 502 так и весит у вас в браузере, то пробуем выполнить следующие действия, которые я опишу ниже.
Запускаем браузер в режиме Инкогнито
В данном режиме браузер стартует с настройками по умолчанию. Соответственно, в этот момент отключены все плагины и расширения, способные повлиять на работу.
Например, для браузера Google Chrome инкогнито запускается сочетанием клавиш Ctrl+Shift+N.
Если вам помог данный совет и error nginx bad 502 больше не появляется, то следует выполнить сброс настроек браузера. Скорее всего виновато какое-то не корректно работающее расширение.
Чистим cookie в браузере.
Многие пользователи писали, что иногда ошибка 502 исчезает после чистки куки браузера. Выше в статье я приводил вам ссылки на инструкции по разным браузерам. Но не все из вас внимательно читают инструкции, поэтому дополню данное руководство.
Яндекс Браузер
Для фанатов данного браузера, чтобы устранить неполадки нужно прописать в адресной строке путь browser://history и щелкнуть клавишу «Enter».
Откроется страница с историей посещений вами различных веб страниц. Чтобы все очистить жмем кнопку «Очистить историю».
В появившемся окне выбираем «За все время» и отмечаем галочкой пункт «Файлы cookie и другие данные сайтов и модулей».В заключении жмем кнопку «Очистить».
Google Chrome
Пользователи Chrome смогут победить ошибку nginx bad сделав следующее.
Открываем выпадающее меню браузера, для этого нажимаем кнопку в виде 3 точек, находящуюся в правом верхнем углу и выбираем пункт «История».
Для быстрого доступа можно нажать сочетание клавиш «Ctrl+H».
В открывшемся окне настроек жмем кнопку «Очистить историю». Далее появится еще одно окно в котором нужно выбрать диапазон «За все время» и отметить пункт «Файлы cookie» и другие данные сайтов.
В заключении жмем кнопку «Удалить данные»
Браузер Opera
Откроется окно, в котором нужно выставить настройки, как показано на скриншоте ниже и нажать на кнопку «Удалить данные».
Internet Explorer
В данном браузере ошибку 502 можно победить, проделав следующие манипуляции.
Открываем меню «Сервис», для этого в правом верхнем углу жмем на кнопку в виде «Шестеренки».
В появившемся списке выбираем пункт «Безопасность» — «Удалить журнал браузера».
Для ленивых: жмем сочетание клавиш на клавиатуре «Ctrl» + «Shift» + «Del».
В открывшемся окне ставим галочку напротив пункта «Файлы cookie и данные веб-сайтов» и жмем кнопку «Удалить».
Mozilla Firefox
В Firefox, так же все делается элементарно. Открываем меню, нажав на кнопку в виде трех полосок, в правой верхней части браузера.
В выпадающем списке выбираем пункт «Библиотека» далее открываем меню «Журнал» и щелкаем по пункту «Удалить историю».
Откроется еще одно окно, в котором ставим галочку в пункте «Куки» и жмем «Удалить сейчас».
Рекомендации для владельцев ресурса
Если ваш сайт часто выдаёт в ответ на запрос ошибку 502 Bad Gateway, то вот некоторые рекомендации, которые помогут справиться с проблемой.
Как часто вам приходится сталкиваться с такой ошибкой? Какие действия помогают исправить ситуацию? Интересует мнение как пользователей сети, так и владельцев сайтов. Поделитесь с нами своими наблюдениями.
Что значит ошибка 502
Код ошибки 502 Bad Gateway в переводе с английского «плохой шлюз».
Запрос пользователя отправляется к серверу, но тот связан еще с одним или несколькими серверами, между которыми образуется цепочка. На одном из серверов цепочки может произойти сбой, поэтому первый сервер выдает данную ошибку.
Например, внутри сервера часто используется связка Nginx + Apache. Веб-сервер Nginx получает запрос от пользователя и передает его на обработку Apache, если веб-сервер Apache по какой-то причине будет недоступен, то Nginx выдаст пользователю ошибку 502.
Ошибка часто возникает из-за того, что сервер перестает справляться с обработкой запросов в следствии большой нагрузки. Перегрузка бывает из-за огромного числа посетителей или из-за большого объема работы сайтов.
Сам клиент не сможет исправить данную ошибку, сделать это сможет только администратор сервера.
Как исправить ошибку 502 Bad Gateway:
Ошибка 502 — результат запроса, который означает, что на стороне сайта возникли проблемы. Проблема чаще всего вызвана неправильной работой оборудования хостера или его неправильной настройкой. Типичной проблемой может быть неправильная настройка DNS или прокси сервера.
Что значит ошибка 502
Ошибка 502 Bad Gateway означает, что запрос с Вашей стороны пришел на сервер, но по каким-то причинам он не смог правильно его обработать, либо не успел. Ваш запрос попадает на сервер, после чего он становится в очередь на обработку. Если сервер находится за шлюзом, то возможно проблема в нем или в работе самого сервера Apache, который и передает на шлюз сообщение об ошибке, которая потом отображается в Вашем браузере.
Возможные причины появления ошибки
Нехватка ресурсов сервера
Одной из главных проблем возникновения такой ошибки является нехватка ресурсов у сервера, из-за чего сервер начинает выдавать ошибку. Проблема обычно происходит из-за недостаточного количества оперативной памяти или нерационального ее использования. Для этого нужно посмотреть нагрузку и потребляемые ресурсы в диспетчере сервера, после чего нужно определить затрачиваемые ресурсы. Если Вы выходите за рамки своего тарифного плана хостинга, то срабатывает ограничение, из-за которого и возникает ошибка. произойти это может и на VPS и на виртуальном хостинге.
Если на сервере применена связка PHP + FastCGI, то во время перегрузки или из за установленных ограничений может происходить нехватка php-cgi процессов.
Типичные причины, которые могут провоцировать нехватку ресурсов:
1. Слишком большое количество одновременных посетителей для Вашего сервера.
Проблемой может быть автоматизированные системы, которые расходуют ресурсы (роботы поисковых систем, неправильный плагин, который забирает все ресурсы на обработку запроса и т. д.);
2. Хакерская атака на сервер, из-за чего сервер перегружен большим количеством неправильных пакетов для обработки.
3. Если проблема возникает спонтанно на самом обычном виртуальном хостинге, то возможно это оверселлинг, т. е. хостер разместил на сервере столько аккаунтов клиентов что им уже не хватает ресурсов в какие то пиковые промежутки времени.
4. Неправильная конфигурация самого сервера или несовместимость программных и/или аппаратных решений.
5. Если сайт использует внешне подключение, например ресурсы или скрипты другого, (информер счетчика посещений и т. д.) то при возникновении проблемы в источнике приведет к проблемам на Вашем сайте.
6. Если на сайт происходит загрузка больших файлов при плохом соединении.
Ошибки PHP
Причиной могут служить расширения или плагины, которые при завершении своей работы не выдают код завершения своего состояния. Из-за этого система nginx принимает внезапное завершение соединения со службой apache и принимает это за ошибку. Если обычные файлы сайта (любая картинка, файл Robots.txt) открываются без проблем, а при попытке загрузки скрипта у Вас ошибка 502, как ее исправить уже более чем понятно: нужно искать причины именно в расширениях и плагинах.
Как устранить ошибку 502
1. Первым делом нужно проанализировать текущую нагрузку на сервер, а также в момент появления ошибок. Если явно прослеживается большая нагрузка на оперативную память, то следует увеличить ее количество. Так как это жизненно важный ресурс для создания и работы новых процессов обработки информации.
4. Если сайт находится на виртуальном хостинге и есть подозрения на оверселинг и/или плохую настройку конфигурации веб-сервера, есть повод задуматься о смене хостинг провайдера.
Ошибка 502 Bad Gateway: что значит, как исправить
При серфинге в интернете довольно часто выскакивают разного рода ошибки и сбои подключения. Наиболее распространенной является ошибка «502 Bad Gateway», которая дословно переводится как «плохой шлюз». В статье мы укажем на основные причины такой ошибки и распишем все действия, которые нужно выполнить пользователю для её устранения.
Ошибка 502 Bad Gateway означает сброс соединения с серверами сайта, что связано с долгим временем подключения или отсутствием ответа от сервера web-страницы.
Причина №1: проблема на стороне сайта
В львиной доле случаев появление ошибки «502 Bad Gateway» вызвано проблемами со стороны серверов или хостинга web-страницы. Чаще всего конкретную причину назвать очень сложно и понять её сможет только владелец/администратор сайта.
Среди самых распространенных проблем, можно выделить такие: перегрузка или DDOS атака на сервера сайта, неправильные настройки DNS и прокси серверов, проблема технического характера у хостинга, проблема с кодом сайта или его плагинами (ошибки PHP). Также реальная причина может скрываться в блокировке сайта Роскомнадзором, из-за нарушения законодательства РФ.
В любом случае: при появлении ошибки «502 Bad Gateway» следует немного подождать. Возможно владелец ресурса уже проинформирован о сбое в работе сайта и приступит к исправлению ситуации. С вашей стороны можете попробовать проинформировать владельца через компанию хостинг (поможет сервис whois.ru), либо через привязанные к сайту странички в социальных сетях.
Причина №2: неполадки в вашей сети
Если со временем ошибка 502 Bad Gateway не исчезает — есть смысл «подергать» настройки вашей сети:
Причина №3: проблема в вашем IP
Бывает и такое, что прописанные настройки сети у пользователя сбрасывают запрошенное соединение, либо наоборот — сервера сайта блокируют подключение с вашего IP. Что бы исключить этот вариант — рекомендуется использовать соединение через VPN. Эта программка меняет прописанный IP-адрес на виртуальный, в следствии чего запрос к серверам будет выполнятся из «другого» места.
Для высокоскоростного VPN можно использовать сторонние программы или расширения для браузера. В последнем случае помогут расширения Hola VPN, ZenMate, uVPN и другие. В браузере Опера, функция впн идет по умолчанию.
VPN-программа WINDSCRIBE
Такой подход часто помогает, если ваш провайдер работает в серой IP-зоне, которая имеет значительные ограничения и её адреса заблокированы. Самый простой пример — санкции в Крыму, из-за чего отсутствует доступ ко многим международным и российским сервисам. К примеру, жители Крыма сообщали, что при попытке открыть онлайн-сервис переводов от банка Тинькофф, выскакивала ошибка «502 Bad Gateway».
Если в вашем случае подключение через VPN решит ошибку «502 Bad Gateway» — рекомендую обратиться к вашему провайдеру и в поддержку сайта. В случае с провайдером есть вариант с обновлением DNS-адресов, который решит ошибку. В случае с поддержкой сайта — вам подскажут, по каким причинам сервис заблокирован в указанном регионе.
Заключение
Подведем краткий итог всего вышеописанного. Если выскакивает ошибка «502 Bad Gateway» — с большой долей вероятности проблема в серверах сайта и от вас ничего не зависит, поэтому рекомендуем подождать. Если вы обнаружили, что подключение через VPN решает проблему — обратитесь к своему провайдеру или владельцу сайта для получения инструкций.
7 способов как исправить ошибку 502 Bad Gateway.
Когда дело доходит до проверки веб-сайтов в интернете, вы можете столкнуться с различными ошибками. Одной из самых известных и популярных среди всех является ошибка «502 Bad Gateway». «>В то время как ваше интернет-соединение или компьютер не имеют к этому никакого отношения, поскольку проблема связана с веб-сайтом. Тем не менее, проверка своего соединения всегда стоит того.
Итак, в этой статье мы собираемся обсудить некоторые из наиболее известных способов исправления ошибки.
Что такое ошибка «502 Bad Gateway»?
Для облегчения понимания отображается ошибка «502 Bad Gateway Error», когда веб-сервер не может получить действительный ответ от входящего сервера.
Каждый раз, когда вы заходите на веб-сайт, ваш веб-браузер отправляет запросы на веб-сервер.
После обработки запроса веб-сервер отправляет обратно запрошенные ресурсы.
Теперь используется термин 502, поскольку это обозначенный код состояния HTTP, используемый веб-сервером для определения ошибок, связанных с сервером.
Есть множество причин, по которым вы можете получить такой ответ.
Во-первых, между двумя серверами может быть перегрузка сервера или даже проблема с сетью.
Иногда даже неправильная конфигурация брандмауэра может вызвать ошибку «502 Bad Gateway».
Вариация ошибки «502 Bad Gateway»
С множеством веб-браузеров, веб-сервисов и операционных систем вы действительно можете найти различные варианты «502 Bad Gateway».
В этом разделе мы собрали все варианты ошибки «502 Bad Gateway Error», с которыми вы можете столкнуться.
7 способов исправить ошибку «502 Bad Gateway»
Независимо от того, как ошибка представлена вам, с вашей машиной все в порядке.
В большинстве случаев это что-то со стороны сервера.
При этом есть еще некоторые исправления, которые вы можете попробовать со своей стороны.
1. Обновите страницу
Это само собой разумеется, но обновление вашей веб-страницы может мгновенно решить вашу проблему.
Фактически, в большинстве случаев ошибка «502 Bad Gateway Error» носит временный характер.
Вы можете просто перезагрузить страницу с помощью обновить страницу в браузере или нажатием клавиш F5, Ctrl + F5 или CMD + R.
Скорее всего, хост-сервер может испытать перегрузку, и ваш веб-сайт скоро появится в сети.
Тем временем вы также можете попробовать загрузить веб-сайт в другом браузере, чтобы проверить, сохраняется ли проблема.
2. Проверка, доступен ли этот веб-сайт для всех
Если вам не удалось связаться с каким-либо веб-сайтом, всегда полезно проверить, связана ли проблема с вашей стороной или другие люди тоже испытывают те же самые проблемы.
На самом деле существует множество веб-сайтов и инструментов, которые могут оказать вам необходимую помощь.
Оба сайта работают одинаково.
Все, что вам нужно сделать, это вставить URL-адрес, который вы предпочитаете проверить, и вы получите соответствующие результаты.
В случае, если вы получите сообщение о том, что веб-сайт недоступен для всех, вы вряд ли сможете что-либо сделать со своей стороны.
Напротив, если отчет показывает, что веб-сайт работает, вам необходимо проверить соединение на своем конце.
Вы всегда можете попробовать другие советы, упомянутые ниже.
3. Выберите другой браузер
Как указывалось ранее, всегда есть вероятность, что ваш веб-браузер является основной проблемой для ошибки «502 Bad Gateway».
Самое простое решение — просто проверить веб-сайт в другом веб-браузере.
Вы можете использовать Microsoft Edge, Mozilla Firefox, Google Chrome или Apple Safari.
Если сайт не открывается, значит, проблема не в вашем браузере.
4. Очистка кэша и файлов cookie веб-сайта
Если вы пробовали другой веб-браузер и проблема была устранена, значит, с вашим основным браузером что-то не так.
Фактически, любой устаревший кэш или поврежденный файл может быть причиной ошибки «502 Bad Gateway Error».
Вы всегда можете обратиться к нашим статьям, чтобы получить более подробные инструкции по удалению кэша или файлов cookie вашего веб-сайта.
После успешного удаления файлов вы можете попробовать открыть веб-сайт, если проблема решена.
5. Проверка подключаемых модулей и расширений браузера
Иногда плагины и расширения браузера могут вызывать множество проблем при попытке открыть определенные веб-страницы.
Вы всегда можете попробовать отключить расширения и проверить, открывается сайт или нет.
В случае, если ошибка «502 Bad Gateway Error» устранена, вероятно, это был один из плагинов, вызывающий эту ошибку.
Попробуйте включить плагины один за другим, чтобы выявить виновника.
6. Перезагрузка устройства
Вы будете удивлены, узнав, сколько проблем с вашим компьютером можно легко решить, просто перезагрузив устройство.
Теперь, когда вы проверили все инструменты и поменяли разные веб-браузеры, проблема все еще сохраняется.
В таких обстоятельствах мы рекомендуем просто перезагрузить компьютер вместе с сетевым устройством.
Используйте это исправление как последнее средство решения проблемы.
7. Изменение DNS-сервера
Скорее всего, проблема с DNS также может вызвать ошибку «502 Bad Gateway Error».
Хотя вы не можете полностью рассматривать то же самое как исправление, всегда стоит попробовать.
Тем не менее, это также совершенно легко изменить.
В большинстве случаев DNS-сервер настраивается вашим интернет-провайдером.
Замена его на любой сторонний DNS-сервер, включая Google DNS или OpenDNS, может оказаться полезным.
Подведение итогов: ошибка «502 Bad Gateway»
Итак, это был список различных способов, с помощью которых вы можете фактически устранить и исправить ошибку «502 Bad Gateway Error».
Обычно это все, что вы можете сделать со своей стороны.
Troubleshooting HTTP 502.2 Bad Gateway error in CGI applications
Tools Used in this Troubleshooter:
This material is provided for informational purposes only. Microsoft makes no warranties, express or implied.
Overview
You have a Web site that is hosted on Internet Information Services (IIS) 7.0. When you visit the Web site in a Web browser, you may receive an error message that resembles the following:
This problem occurs because the CGI process terminates unexpectedly before the CGI process sends a response back to IIS 7.0
Troubleshooting
Scenario: When sending a request to a CGI application running via IIS, the user is presented with the following error instead of the expected response:
Capturing a Netmon trace shows this sort of information:
Capture FREB log for the HTTP error message and locate which module is throwing this error message.
Troubleshoot the CGI process executable file to determine why the CGI process terminates unexpectedly. You may have to generate a memory dump file of the CGI process when the access violation occurs.https://support.microsoft.com/?id=150835
This problem occurs when the CGI application does exactly what the error suggests: inserts invalid data into the HTTP Header value(s) that is sends to IIS as part of its response. In IIS 6 with Windows 2003 SP1 installed, you can use Enterprise Tracing for Windows (ETW Tracing) to see exactly what the CGI is returning.
Capturing a Trace file using ETW Tracing
Copy the ETWSetup.zip file attached to this email to the IIS6 Server.
Extract it on the server.
Open this folder from the command prompt.
Type iis6trace-start.cmd to start the tracing.
Reproduce the issue.
Type iis6trace-stop.cmd to stop the tracing.
At this point, we should have an iistrace_etl.etl file in that folder.
Please zip up that file and send it to Microsoft Support Engineer.
Support engineer can help you convert ETL file into XML.
Here is an example trace file from this sort of CGI problem:
The request to the CGI starts at line 391:
Line 441 shows the problem in the CGI:
Line 446 then shows the 502 that is sent to the client. It is in fact a 502.2 (substatus of 2):
The request is processed by IIS, we see it is for a CGI, and we pass it along to the CGI. The CGI starts its processing at line 405:
The difference between a 502, 503 and 504 error
January 3, 2017
We all come across website errors at some point, and every website out there has inevitably experienced their share of 404 and 500 status codes, which are shown when a URL is not found either due to their typo or a broken link (404), and when there is a general server error (500).
There are many other less well known status codes in the 400 and 500 range: Those HTTP status codes beginning with 4 are errors on the client side, and codes beginning with 5 are errors on the side of the website server.
Some of the common 500 error messages that websites may encounter are 502, 503, and 504, which are all related to the website server being unable to fill a request that should be valid. These codes provide both the user and the website owner with additional information as to why a page is not loading. Websites can utilize logs and alerts to keep track of how often these errors occur and be notified when errors are occurring so that they can be resolved if needed.
502 Bad Gateway
A 502 error means that a website server that is serving as a reverse proxy for the website origin server (for example, a CDN PoP) did not receive a valid response from the origin server. This may be because the origin server is experiencing issues, there is an invalid or incorrect DNS name, or because a firewall on the origin server has blocked the reverse proxy server request.
This may also occur when requests at the origin server are taking several minutes to complete and a caching tool such as Varnish Cache has been instructed to timeout after a set number of seconds. Varnish Cache has a default timeout of 60 seconds, which Section recommends keeping for security and alerting reasons.
503 Service Unavailable
To avoid serving 503 errors due to an overload of visitors, we recommend using a Content Delivery Network and caching tool so that more of your requests can be served from the CDN and cache.
504 Gateway Timeout
Similar to the 502 error, the 504 Gateway Timeout error occurs if the server that is acting as a proxy for the website origin server did not receive a response from the website origin server within a set time period. This may indicate an issue with the DNS host or hosting company, or with the connection or configuration between the reverse proxy servers and the website origin server.
Troubleshooting 500 errors
502 and 504 errors are related to a bad gateway, meaning that while the reverse proxy server is operational, something it needs to collect from the origin server is not working, or the connection between the reverse proxy server and the origin server is broken. To troubleshoot this issue, websites should check that their origin server and all the servers it needs to access are running correctly, and then check the configuration between the origin server and reverse proxy server (such as the CDN PoP or locally installed Varnish Cache server). You should also check that your firewall is not accidentally blocking legitimate traffic, your DNS name is set up correctly, and your origin hosting provider is not down.
503 errors are often expected when your website is going through downtime in order to make updates or changes. They may also be triggered by a large influx of traffic to your website. If your website does not scale well, we suggest exploring utilizing a CDN such as Section’s and/or a caching reverse proxy such as Varnish Cache. To learn more please contact us or sign up for a trial account to explore our features free for 2 weeks.
Ошибка 502 bad gateway что это значит и как ее решить
Ошибка 502 bad gateway что это значит. Что делать пользователю интернета, если он видит белый экран с этой надписью?
Систематический серфинг интернет-страниц чреват периодическими появлениями разного рода ошибок, в частности, 502 bad gateway в одноклассниках и прочих ресурсах.
Содержание:
Сразу скажем, что это никакой не вирус и проверять компьютер на «заразу» не потребуется. Впрочем, переустанавливать Windows тоже.
Такие сообщения являются следствием нескольких факторов:
Если опустить всяческие технические нюансы, то ошибка 502 говорит о том, что браузер получил некорректные данные от сервера, к которому вы ссылаетесь в данный момент.
Как результат, обозреватель «выдает» соответствующую заставку. Как исправить 502 bad gateway?
Пути решения проблемы
Первым делом попробуйте локализовать причину. Откройте другой сайт и ресурс. Желательно пользоваться теми сервисами, которые территориально размещены там же, где и вы (в пределах государства).
В частности, если вы живете в России, а возникает 502 bad gateway в вк либо одноклассниках, посетите какой-нибудь федеральный новостной сайт.
Если он работает – значит, с ВКонтакте какие-то проблемы и нужно подождать либо почистить cookie-файлы.
Собственно, так проверяется доступ к сети в целом.
Что касается корпоративного сектора (офисы, предприятия). Доступ к интернету в таких местах получают локально.
Иными словами, ваш компьютер соединен с глобальной сетью не напрямую, а косвенно.
В случае возникновения поломки лучше позвать системного администратора. Хотя почистить cookies не помешает. Как это сделать?
Рассмотрим 4 основных браузера, которыми пользуются чаще всего:
Процедура очистки у каждого своя, поэтому будем рассматривать каждый случай отдельно.
Chrome
Чтобы избавиться от cookies в этом обозревателе, нужно открыть настройки.
Прокручиваем список параметров и находим кнопку «очистить историю».
Видим целый спектр настроек.
Для начала выбираем период чистки (1). Обычно значение оставляют на отметке «за все время», чтобы избавиться от всего мусора, который скопился за период использования браузером.
Первые 4 пункта отмечены галочкой (2). Первый, второй и четвертый удалят всю историю просмотра интернет-страниц.
Так можно дополнительно освободить до 1–2 Гб на жестком диске. И заодно оставьте галочку на cookies, ради которых все и затевалось. Жмем на очистку (3) и ждем окончания процесса.
Читайте также:
Opera
Здесь почистить историю еще проще. Для начала жмем на логотип браузера в левом верхнем углу и ищем пункт «история».
Переключаем взор на правый верхний угол и видим кнопку «очистить историю…».
Видим здесь такой же набор параметров, как в Chrome.
Остается лишь поставить галочки в тех местах, которые отмечены на скрине и нажать на очистку.
Firefox
Ситуация здесь идентичная первым двум вариантам. Открываем параметры в поиске кнопки «настройки».
Переключаемся на «приватность».
Система предлагает нам удалить отдельные куки-файлы. Соглашаемся и кликаем по ссылке.
Видим две кнопки.
Internet Explorer
Несмотря на то, что в «природе» существует несколько стабильных, быстрых и хороших браузеров, некоторые до сих пор не приемлют ничего, кроме старого доброго IE.
Он изначально установлен в Windows в качестве браузера по умолчанию, за что столь популярен.
Для чистки cookies нам понадобится найти пункт «сервис».
Загвоздка в том, что изначально он невидим. Нажмите кнопку Alt, чтобы открыть эту надстройку
Кликаем по меню, выбирая команду «удалить журнал…»
По сути, нас интересуют только куки-файлы. Оставляем галочку напротив них, после чего удаляем выбранное.
Итак, чистка произведена, что информирует нас об одной вещи: мы не имеем к ошибке никакого отношения.
Если она вызывается повторно, значит, проблема либо у провайдера, предоставляющего нам доступ, либо на самом ресурсе.
Читайте также:
Альтернативные способы лечения ошибки
Что значит 502 bad gateway для тех, кто держит собственные серверные мощности.
По большому счету, они и являются поставщиками доступа к сети либо предлагают услуги по хранению данных с сайта. Ситуация общая, без вовлечения в технические особенности.
502 ошибка может означать следующее:
Грубо говоря, команда «одноклассников» DDoS-ит сервера ВКонтакте.
В результате пользователи видят перед собой 502 ошибку и, дожидаясь, пока ВК заработает снова, просматривают содержимое сайта-инициатора.
«Защищающемуся» ничего не остается, как тратить колоссальные средства на дополнительное ПО и фаерволы, чтобы обезопасить себя в дальнейшем.
Если вы видите 502 ошибку, не стоит паниковать и искать телефон провайдера. Для начала воспользуйтесь «подручными» средствами.
Так вы сэкономите немало времени и нервов не только себе, но и операторам call-центров.
502 Bad Gateway — как исправить ошибку
Виды ошибки
Появляться данное сообщение может в разных формулировках. Все зависит от используемого хостинга. При отсутствии доступа к сайту вы можете наблюдать следующие вариации ошибки:
Использовать переводчик для определения сути ошибки не нужно, поскольку со стороны пользователя разницы в них нет. Способы решения проблемы будут одинаковыми.
Проверка доступа к интернету
Первым делом посмотрите, не появляется ли ошибка при переходе на другие сайты. Для этого попробуйте зайти на любой ресурс. Можно тестировать на поисковике «Гугл», социальных сетях или других сайтах, которые вы посещаете чаще всего. Лучше всего посещать федеральные порталы, доступ к которым не должен быть ограничен в любых ситуациях.
Второй способ проверки – это тестирование другого браузера. Если ошибка устранилась, это значит, что проблема на стороне вашего основного браузера. Попробуйте переустановить или обновить программу.
Если такое сообщение появляется на любых сайтах и в любых браузерах, то проблему необходимо искать на вашем компьютере или на стороне провайдера. Появление ошибки исключительно при загрузке определенного сайта обозначает, что неисправность на стороне веб-сайта.
Очистка кэша и cookie
Попробуем устранить появление ошибки с помощью очистки кэш-файлов и cookie в браузере. Эта процедура выполняется приблизительно одинаково во всех популярных программах. Разберемся, как это сделать.
В большинстве браузеров работает комбинация клавиш [knopka]Ctrl[/knopka]+[knopka]Shift[/knopka]+[knopka]Del[/knopka]. С ее помощью осуществляется переход в окно настроек для очистки истории и cookie. При работе с Google Chrome необходимо перевести временной диапазон в положение «Все время». Также обязательно ставьте галочки возле отмеченных пунктов. После этого нажмите на кнопку «Удалить данные»:
Яндекс.Браузер имеет практически аналогичное окно для очистки истории. Здесь также нужно указать пункт «За все время», выбрать очистку кэша и файлов cookie:
Браузер Opera тоже поддерживает данную комбинацию клавиш. При нажатии открывается следующее окно. Во вкладке «Основные» выбирается временной диапазон и отмечаются все пункты:
Mozilla Firefox открывает отдельное окно с функциями очистки. Выставляем настройки со скриншота и жмем на кнопку «Удалить сейчас»:
Окно очистки в стандартном браузере Windows (Microsoft Edge) выглядит следующим образом:
Очистка кэша DNS
Еще одна вещь, которая может стать причиной со стороны компьютера – это кэш DNS. Очистить его можно через командную строку Windows. Делается это следующим образом:
Режим инкогнито в браузере
Чтобы не переустанавливать браузер с нуля, вы можете открыть его в режиме инкогнито. В нем программа не использует плагины и расширения, установленные пользователем, настройки и так далее. Если в режиме инкогнито проблема исчезает, то необходимо искать причину в надстройках и параметрах основного браузера.
Запускается данный режим с помощью комбинации клавиш [knopka]Ctrl[/knopka]+[knopka]Shift[/knopka]+[knopka]N[/knopka] в браузерах Google Chrome и Opera. А в Яндекс.Браузере, Mozilla Firefox и Microsoft Edge используется [knopka]Ctrl[/knopka]+[knopka]Shift[/knopka]+[knopka]P[/knopka].
Если ничего не помогает?
Если перезагрузка не исправила ситуацию, то причина ошибки находится на стороне провайдера или самого веб-ресурса. В первом случае пользователь может обратиться в службу поддержки, оставить жалобу, вызвать мастера и так далее. Проблема будет устраняться провайдером исходя из индивидуальной ситуации.
Если речь идет о массовом отсутствии доступа к сайту, то владельцы сервера быстро устранят поломку. Вам остается только подождать некоторое время или обратить в поддержку сайта, если такая возможность имеется.
Проблемы со стороны веб-сервиса
Ошибка 502 Bad Gateway может появляться при использовании виртуальных хостингов и арендованных серверов. К самым распространенным неисправностям можно отнести следующие:
Во всех случаях проблему нужно решать индивидуально после анализа поведения сайта и серверов. Рекомендуется связаться с поддержкой хостинг-провайдера для прояснения ситуации, если исправить проблему самостоятельно не получается.
Видеоинструкция
Обязательно ознакомьтесь с представленным роликом. В нем наглядно разбираются все способы решения проблемы.
Заключение
Теперь вы знаете перевод ошибки 502 Bad Gateway на русский язык, а также сможете ее исправить, если вина не лежит на стороне сервера.
Что за ошибка 502 — причина и решение
Ошибка 502 bad gateway – довольно специфическая проблема, которая может проявить себя при активном серфинге на просторах всемирной паутины. Причем возникать она может при попытке перехода на тот же ресурс, на который совершал пользователь вход немногим ранее.
В чем причина?
Итак, что это значит и как исправить? Данный код ошибки говорит о том, что система попыталась получить доступ к удаленному серверу, но не может правильно завершить процесс. Итог — error 502 http.
Решение
После того, как мы выяснили что это – ошибка 502, можно приступать к лечению.
Первоначальный шаг – попробовать запустить сайт, который гарантированно является рабочим. Можно, например, попросить друзей, родственников, сослуживцев зайти на какой-то ресурс со своего персонального компьютера. После этого, повторить процедуру на собственном ПК.
Если надежный ресурс не отвечает, то возможно, отсутствует возможность подключения к интернету. Следует проверить его наличие у себя или обратиться к поставщику услуг – провайдеру.
Если сайт открывается, а первоначально введенный адрес приводит к надписи «ошибка получения данных сервера 502 bad gateway», необходимо разобраться с cookies. Для каждого интернет-браузера решение этого вопроса заключается в схожих, но несколько разных шагах. Мы предлагаем варианты для самых распространенных сегодня приложений:
К аналогичному развитию событий может привести отсутствие прав доступа. Обычно это бывает в корпоративных сетях, где существует администратор, который занимается подобными вопросами. Следует обратиться к нему и узнать – происходило ли ограничение на доступ или нет?
Если ни один из рассмотренных способов не смог исправить ситуацию ошибки 502 bad gateway, то высока вероятность того, что запрашиваемый адрес уже не существует или с ресурсом, расположенным но нему, произошла какая-то неприятность. В этой ситуации вы ничего сделать не сможете – остается только ждать и верить, что желанный сайт возобновит свою функциональность.
Http Request fails with response status code : 502
In a loop I’m hitting like 1000 GET requests. Since there are too many requests and the gateway could not handle it, it fails with the error code 502. Whats the best way to solve this. My code as bellow.
My Singleton Network later that ill be calling in the above method as bellow.
Inside the above class I use a generic method to call HTTP request (Here Im not showing the full method with all the parameters, but you can get an idea what it looks like)
1 Answer 1
You could use DispatchSemaphore to limit the number of parallel running tasks, like this:
The example uses a custom concurrent queue (1) to create tasks that will start the network fetching. In the task, we first wait (2) for the semaphore. This call will simply decrement the semaphore’s counter, as long as the counter is larger than zero. If the counter is zero, the wait call blocks.
In the success (3a) and error (3b) handlers, we call signal on the semaphore, to indicate that we’ve finished the network call. signal will increment the counter or wake up any waiting call.
This construct ensures that at utmost 500 getData calls are running in parallel
Error: Request failed with status code 502 #2802
Comments
xiaomuzizier commented Mar 5, 2020
Describe the issue
A clear and concise description of what the issue is.
In my development,I have this error:
Error: Request failed with status code 502
at createError (/Users/ninaqqli/Desktop/lopan/lopan-server/node_modules/axios/lib/core/createError.js:16:15)
at settle (/Users/ninaqqli/Desktop/lopan/lopan-server/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/Users/ninaqqli/Desktop/lopan/lopan-server/node_modules/axios/lib/adapters/http.js:236:11)
at IncomingMessage.emit (events.js:203:15)
at IncomingMessage.EventEmitter.emit (domain.js:466:23)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Example Code
Code snippet to illustrate your question
Expected behavior, if applicable
A clear and concise description of what you expected to happen.
Environment:
Additional context/Screenshots
Add any other context about the problem here. If applicable, add screenshots to help explain.
The text was updated successfully, but these errors were encountered:
Ошибка 502 — что это значит и как исправить
Ошибка 502 Bad Gateway – это код состояния HTTP, который означает, что один сервер в Интернете получил неверный ответ от другого сервера. Ошибки 502 Bad Gateway полностью не зависят от вашей конкретной настройки интернета, то есть вы можете увидеть ее в любом браузере, в любой операционной системе и на любом устройстве.
Ошибка 502 Bad Gateway отображается в окне интернет-браузера, как и веб-страницы.
Как появляется ошибка 502 Bad Gateway
Ошибку 502 Bad Gateway можно встретить практически на каждом веб-сайте Интернета. Хотя это довольно редко, разные веб-серверы описывают эту ошибку по-разному.
Ниже приведены несколько общих способов написания и поиска этой ошибки в Интернете:
Известная в Твиттере ошибка, в которой говорится, что Твиттер переполнен, на самом деле является ошибкой 502 Bad Gateway (хотя ошибка 503 имеет больше смысла).
Ошибка Bad Gateway, полученная в Центре обновления Windows, создает код ошибки 0x80244021 или сообщение WU_E_PT_HTTP_STATUS_BAD_GATEWAY.
Когда службы Google, такие как Google Search или Gmail, испытывают ошибку 502 Bad Gateway, они часто показывают ошибку сервера, а иногда и просто 502, на экране.
Причина 502 ошибки Bad Gateway
Ошибки Bad Gateway часто бывают вызваны проблемами между онлайн-серверами, которые вы не можете контролировать. Тем не менее, иногда, нет реальной проблемы, но ваш браузер думает, что есть одна из проблем с вашим браузером, проблема может быть с вашим домашним сетевым оборудованием или по какой-то другой причине, находящейся под вашим контролем.
Как исправить 502 ошибку Bad Gateway
Ошибка 502 Bad Gateway часто является сетевой ошибкой между серверами в Интернете, то есть проблема не связана с вашим компьютером или подключением к Интернету.
Однако, возможно, что с вашей стороны что-то не так, вот некоторые исправления, которые стоит попробовать:
Попробуйте снова загрузить URL-адрес, нажав F5 или Ctrl + R на клавиатуре или нажав кнопку обновления / перезагрузки.
Хотя ошибка 502 Bad Gateway обычно указывает на сетевую ошибку вне вашего контроля, она может быть чрезвычайно временной. Повторная попытка страницы часто будет успешной.
Начните новый сеанс браузера, закрыв все открытые окна браузера, а затем открыв новый. Затем попробуйте открыть веб-страницу снова.
Возможно, ошибка 502, которую вы получили, произошла из-за проблемы на вашем компьютере, возникшей когда-то во время этого использования вашего браузера. Простой перезапуск самой программы браузера может решить проблему.
Удалите куки вашего браузера. По тем же причинам, которые упоминались выше для кэшированных файлов, очистка сохраненных файлов cookie может исправить ошибку 502
Если вы не хотите удалять все свои cookie-файлы, сначала попробуйте удалить только те cookie-файлы, которые относятся к сайту, на котором появляется ошибка 502. Лучше всего удалить их все, но не помешает вначале попробовать явно применимые.
Обращение к сайту напрямую также может быть хорошей идеей. Скорее всего, предполагая, что они виноваты, администраторы веб-сайта уже работают над устранением причины ошибки 502 Bad Gateway, но не стесняйтесь сообщить им об этом.
Смотрите нашу контактную страницу веб-сайта для списка контактов для популярных веб-сайтов. Большинство веб-сайтов имеют учетные записи в социальных сетях, которые они используют для поддержки своих услуг. У некоторых даже есть телефон и контакты по электронной почте.
Troubleshooting bad gateway errors in Application Gateway
Learn how to troubleshoot bad gateway (502) errors received when using Azure Application Gateway.
This article uses the Azure Az PowerShell module, which is the recommended PowerShell module for interacting with Azure. To get started with the Az PowerShell module, see Install Azure PowerShell. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.
Overview
Network Security Group, User Defined Route, or Custom DNS issue
Cause
If access to the backend is blocked because of an NSG, UDR, or custom DNS, application gateway instances can’t reach the backend pool. This causes probe failures, resulting in 502 errors.
The NSG/UDR could be present either in the application gateway subnet or the subnet where the application VMs are deployed.
Similarly, the presence of a custom DNS in the VNet could also cause issues. A FQDN used for backend pool members might not resolve correctly by the user configured DNS server for the VNet.
Solution
Validate NSG, UDR, and DNS configuration by going through the following steps:
If present, ensure that the DNS server can resolve the backend pool member’s FQDN correctly.
Problems with default health probe
Cause
502 errors can also be frequent indicators that the default health probe can’t reach back-end VMs.
When an application gateway instance is provisioned, it automatically configures a default health probe to each BackendAddressPool using properties of the BackendHttpSetting. No user input is required to set this probe. Specifically, when a load-balancing rule is configured, an association is made between a BackendHttpSetting and a BackendAddressPool. A default probe is configured for each of these associations and the application gateway starts a periodic health check connection to each instance in the BackendAddressPool at the port specified in the BackendHttpSetting element.
The following table lists the values associated with the default health probe:
Probe property | Value | Description |
---|---|---|
Probe URL | http://127.0.0.1/ | URL path |
Interval | 30 | Probe interval in seconds |
Time-out | 30 | Probe time-out in seconds |
Unhealthy threshold | 3 | Probe retry count. The back-end server is marked down after the consecutive probe failure count reaches the unhealthy threshold. |
Solution
Problems with custom health probe
Cause
Custom health probes allow additional flexibility to the default probing behavior. When you use custom probes, you can configure the probe interval, the URL, the path to test, and how many failed responses to accept before marking the back-end pool instance as unhealthy.
The following additional properties are added:
Probe property | Description |
---|---|
Name | Name of the probe. This name is used to refer to the probe in back-end HTTP settings. |
Protocol | Protocol used to send the probe. The probe uses the protocol defined in the back-end HTTP settings |
Host | Host name to send the probe. Applicable only when multi-site is configured on the application gateway. This is different from VM host name. |
Path | Relative path of the probe. The valid path starts from ‘/’. The probe is sent to |
Interval | Probe interval in seconds. This is the time interval between two consecutive probes. |
Time-out | Probe time-out in seconds. If a valid response isn’t received within this time-out period, the probe is marked as failed. |
Unhealthy threshold | Probe retry count. The back-end server is marked down after the consecutive probe failure count reaches the unhealthy threshold. |
Solution
Validate that the Custom Health Probe is configured correctly as the preceding table. In addition to the preceding troubleshooting steps, also ensure the following:
Request time-out
Cause
When a user request is received, the application gateway applies the configured rules to the request and routes it to a back-end pool instance. It waits for a configurable interval of time for a response from the back-end instance. By default, this interval is 20 seconds. In Application Gateway v1, if the application gateway does not receive a response from back-end application in this interval, the user request gets a 502 error. In Application Gateway v2, if the application gateway does not receive a response from the back-end application in this interval, the request will be tried against a second back-end pool member. If the second request fails the user request gets a 502 error.
Solution
Application Gateway allows you to configure this setting via the BackendHttpSetting, which can be then applied to different pools. Different back-end pools can have different BackendHttpSetting, and a different request time-out configured.
Empty BackendAddressPool
Cause
If the application gateway has no VMs or virtual machine scale set configured in the back-end address pool, it can’t route any customer request and sends a bad gateway error.
Solution
Ensure that the back-end address pool isn’t empty. This can be done either via PowerShell, CLI, or portal.
The output from the preceding cmdlet should contain non-empty back-end address pool. The following example shows two pools returned which are configured with a FQDN or an IP addresses for the backend VMs. The provisioning state of the BackendAddressPool must be ‘Succeeded’.
Unhealthy instances in BackendAddressPool
Cause
If all the instances of BackendAddressPool are unhealthy, then the application gateway doesn’t have any back-end to route user request to. This can also be the case when back-end instances are healthy but don’t have the required application deployed.
Solution
Ensure that the instances are healthy and the application is properly configured. Check if the back-end instances can respond to a ping from another VM in the same VNet. If configured with a public end point, ensure a browser request to the web application is serviceable.
Next steps
If the preceding steps don’t resolve the issue, open a support ticket.
Request failed with status code 502
Troubleshooting 502 Errors in ARR
by Richard Marr
Tools Used in this Troubleshooter:
This material is provided for informational purposes only. Microsoft makes no warranties, express or implied.
Figure 1 (Click image to expand)
The root cause of the error will determine the actions you should take to resolve the issue.
502.3 Timeout Errors
The error code in the screenshot above is significant because it contains the return code from WinHTTP, which is what ARR uses to proxy the request and identifies the reason for the failure.
You can decode the error code with a tool like err.exe. In this example, the error code maps to ERROR_WINHTTP_TIMEOUT. You can also find this information in the IIS logs for the associated website on the ARR controller. The following is an excerpt from the IIS log entry for the 502.3 error, with most of the fields trimmed for readability:
sc-status | sc-substatus | sc-win32-status | time-taken |
---|---|---|---|
502 | 3 | 12002 | 29889 |
The win32 status 12002 maps to the same ERROR_WINHTTP_TIMEOUT error reported in the error page.
What exactly timed-out?
We investigate this a bit further by enabling Failed Request Tracing on the IIS server. The first thing we can see in the failed request trace log is where the request was sent to in the ARR_SERVER_ROUTED event. The second item I have highlighted is what you can use to track the request on the target server, the X-ARR-LOG-ID. This will help if you are tracing the target or destination of the HTTP request:
77. | ARR_SERVER_ROUTED | RoutingReason=»LoadBalancing», Server=»192.168.0.216″, State=»Active», TotalRequests=»3″, FailedRequests=»2″, CurrentRequests=»1″, BytesSent=»648″, BytesReceived=»0″, ResponseTime=»15225″ 16:50:21.033 |
---|---|---|
78. | GENERAL_SET_REQUEST_HEADER | HeaderName=»Max-Forwards», HeaderValue=»10″, Replace=»true» 16:50:21.033 |
79. | GENERAL_SET_REQUEST_HEADER | HeaderName=»X-Forwarded-For», HeaderValue=»192.168.0.204:49247″, Replace=»true» 16:50:21.033 |
80. | GENERAL_SET_REQUEST_HEADER | HeaderName=»X-ARR-SSL», HeaderValue=»», Replace=»true» 16:50:21.033 |
81. | GENERAL_SET_REQUEST_HEADER | HeaderName=»X-ARR-ClientCert», HeaderValue=»», Replace=»true» 16:50:21.033 |
82. | GENERAL_SET_REQUEST_HEADER | HeaderName=»X-ARR-LOG-ID», HeaderValue=»dbf06c50-adb0-4141-8c04-20bc2f193a61″, Replace=»true» 16:50:21.033 |
83. | GENERAL_SET_REQUEST_HEADER | HeaderName=»Connection», HeaderValue=»», Replace=»true» 16:50:21.033 |
The following example shows how this might look on the target server’s Failed Request Tracing logs; you can validate that you have found the correct request by matching up the «X-ARR-LOG_ID» values in both traces.
185. | GENERAL_REQUEST_HEADERS Headers=»Connection: Keep-Alive Content-Length: 0 Accept: */* Accept-Encoding: gzip, deflate Accept-Language: en-US Host: test Max-Forwards: 10 User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0) X-Original-URL: /time/ X-Forwarded-For: 192.168.0.204:49247 X-ARR-LOG-ID: dbf06c50-adb0-4141-8c04-20bc2f193a61 |
---|---|
345. | GENERAL_FLUSH_RESPONSE_END BytesSent=»0″, ErrorCode=»An operation was attempted on a nonexistent network connection. (0x800704cd)» 16:51:06.240 |
In the above example, we can see that the ARR server disconnected before the HTTP response was sent. The timestamp for GENERAL_FLUSH_RESPONSE_END can be used as a rough guide to find the corresponding entry in the IIS logs on the destination server.
date | time | s-ip | cs-method | cs-uri-stem | cs-uri-query | s-port | cs-username | sc-status | sc-substatus | sc-win32-status | time-taken |
---|---|---|---|---|---|---|---|---|---|---|---|
2011-07-18 | 16:51:06 | 92.168.0.216 | GET | /time/ | — | 80 | — | 200 | 0 | 64 | 45208 |
Note that IIS on the destination server logged an HTTP 200 status code, indicating that the request completed successfully. Also note that the win32 status has changed to 64, which maps to ERROR_NETNAME_DELETED. This generally indicates that the client (ARR being the ‘client’ in this case) had disconnected before the request completed.
Only the ARR server is reporting a timeout, so that is where we should look first.
In the IIS log entry from the ARR server, we can see that the time-taken is very close to 30 seconds, but the member server log shows that it took 45 seconds (45208 ms) to send the response. This suggests that ARR is timing the request out, and if we check the proxy timeout in the server farm’s proxy settings, we will see that it is set to 30 seconds by default.
So in this case we can clearly see that the ARR timeout was shorter than the execution of the request. Therefore, you would want to investigate whether this execution time was normal or whether you would need to look at why the request was taking longer than expected. If this execution time was expected and normal, increasing the ARR timeout should resolve the error.
Other possible reasons for ERROR_WINHTTP_TIMEOUT include:
Looking at the first two examples, ResolveTimeout and ConnectTimeout, the troubleshooting methodology outlined above would not work. This is because you would not see any traffic on the target server and therefore would not know the error code. Thus in this case of ResolveTimeout or ConnectTimeout you would want to capture a WinHTTP trace for additional insight. See the WinHTTP/WEBIO Tracing section of this troubleshooter as well as the following blogs for additional examples on troubleshooting and tracing:
502.3 Connection Termination Errors
Figure 2 (Click image to expand)
The error 0x80072efe corresponds to ERROR_INTERNET_CONNECTION_ABORTED. The request can be traced to the server that actually processed it using the same steps used earlier in this troubleshooter, with one exception; while Failed Request Tracing on the destination server shows the request was processed on the server, the associated log entry does not appear in the IIS logs. Instead, this request is logged in the HTTPERR log as follows:
The error below is another example of an invalid response from the member server:
Figure 3 (Click image to expand)
In this example, ARR started to receive data from the client but something went wrong while reading the request entity body. This results in the 0x80072f78 error code being returned. To investigate further, use Network Monitor on the member server to get a network trace of the problem. This particular error example was created by calling Response.Close() in the ASP.net page after sending part of the response and then calling Response.Flush(). If the traffic between the ARR server and the member servers is over SSL, then WinHTTP tracing on Windows Server 2008 or WebIO tracing on Windows Server 2008 R2 may provide additional information. WebIO tracing is described later in this troubleshooter.
502.4 No appropriate server could be found to route the request
The HTTP 502.4 error with an associated error code of 0x00000000 generally indicates that all the members of the farm are either offline, or otherwise unreachable.
Figure 4 (Click image to expand)
The first step is to verify that the member servers are actually online. To check this, go to the «servers» node under the farm in the IIS Manager.
Figure 5 (Click image to expand)
Servers that are offline can be brought back online by right-clicking on the server name and choosing «Add to Load Balancing». If you cannot bring the servers back online, verify the member servers are reachable from the ARR server. The «trace Messages» pane on the «servers» page may also provide some clues about the problem. If you are using Web Farm Framework (WFF) 2.0, you may receive this error if the application pool restarts. You will need to restart the Web Farm Service to recover.
Usually, Network Monitor will provide you with the information you need to identify exactly what is timing out, however there are times (such as when the traffic is SSL encrypted) that you will need to try a different approach. On Windows 7 and Windows Server 2008R2 you can enable WinHTTP tracing using the netsh tool by running the following command from an administrative command prompt:
Then, reproduce the problem. Once the problem is reproduced, stop the tracing by running the following command from the command prompt:
To analyze the log, open it in Netmon 3.4 or later. Make sure you have set up your parser profile as described here. Scroll through the trace until you find the w3wp.exe instance where ARR is running by correlating with the «UT process name» column. Right click on w3wp and choose «Add UT Process name to display filter». This will set the display filter similar to:
You can further filter the results by changing it to the following:
You will need to scroll through the output until you find the timeout error. In the example below, a request timed out because it took more than 30 seconds (ARR’s default timeout) to run.
In this next example, the content server was completely offline:
Ошибка 502 Bad Gateway: что вызывает ее и как ее исправить
Что такое ошибка 502 Bad Gateway?
В зависимости от веб-сервера, который использует Интернет, например Apache или Nginx, используемый веб-сервер также будет отображаться чуть ниже ошибки, но часть «Ошибка 502, плохой шлюз» всегда будет отображаться, даже если в CDN, поскольку у Cloudflare есть определенный веб-сайт, чтобы показать эту ошибку 502 своим посетителям, это обычно происходит, когда CDN не может должным образом взаимодействовать с исходным веб-сервером для получения контента.
Эта ошибка очень распространена при использовании CDN или сетей распространения контента, и возможно, что в некоторых случаях серверы CDN не могут правильно взаимодействовать с хостинговыми веб-серверами. Пользователь делает веб-запрос на определенную страницу, если она работает с CDN, запрос будет получен непосредственно CDN. Впоследствии из CDN делается запрос к реальному веб-серверу хостинга, именно здесь возникает ошибка связи, и CDN может вернуть пользователю ошибку 502.
Причины возникновения этой неисправности
Как видите, причин, вызывающих эту ошибку, несколько. Хотя в очень немногих случаях мы можем решить эту ошибку самостоятельно, мы дадим вам несколько советов, как попытаться войти на веб-сайт, который возвращает эту ошибку.
Как исправить ошибку 502
Если таким образом сеть по-прежнему не работает, мы ничего не можем сделать, кроме как ждать, пока администраторы страницы, о которой идет речь, наконец решат ее.
Вы когда-нибудь сталкивались с веб-страницей, которая возвращает ошибку 502 Bad Gateway?
15 Best Methods to Fix 502 Bad Gateway Error
Are you frustrated with the error message”502 bad gateway” displaying on your computer again and again? And you are looking for a 502 bad gateway fix? Then you are landed on the right page.
Since 502 bad gateway errors can be triggered due to plenty of reasons, it would be very difficult for anyone to figure out the exact root cause. It is because the problem can range from user-level i.e browser settings to your CDN.
So in this article, we tried to cover all the possible root causes and different methods by which you can easily fix 502 bad Gateway errors. But before that, let us understand what does the error “502 bad gateway” means?
Methods To Fix 502 Bad Gateway
What is a 502 Bad Gateway Error?
The HyperText Transfer Protocol HTTP 502 Bad Gateway error usually comes from the server end and doesn’t have anything to do with your computer locally. This error states there has been an inadequate response from the other server. You can see this error on any device, browser, and operating system.
This error page can be modified by every website, in which case you will see a custom error page instead of the default error page above. Some other common server-side errors that you see are 504 Gateway Timeout Error, Error 500 internal server error, dns_probe_finished_nxdomain.
Different Variations You Might See In The Error
There are different ways in which you might see 502 errors. Let’s have a look at the various messages that you might face due to the 502 error.
If you are experiencing a Server Error or 502 error when trying to access a site, it means that you are seeing a 502 Bad Gateway error. This error is also sometimes shown as :
Impact of 502 bad gateway error on SEO of your Website
If this error displays on your computer screen, again and again, it will have a bad impact on your website reputation as well as on the Search Engines. In the end, it leads to a poor experience for the clients on a clear basis that, nobody needs to manage a site that as often as possible shows errors.
If this error remains too long on your website, probably your website will be completely deindexed on the search engines as your website will not show any data to people leading to high bounce rates and dropping ranks.
5 main reasons that causes 502 Bad Gateway Error
It is an error that you might see because the server was not able to provide a valid response to the request. Several other reasons might lead to a 502 error. Here are the most common reasons.
1. Origin Server Is not Working:
One of the reasons you might experience this error is that the server is not working properly. This means the server is not accessible; there can be many explanations for this, like, either the server is down or there is a connectivity problem or there might be a very high amount of traffic on the server.
2. Domain Name:
Another reason for seeing a 502 Bad Gateway error is that the domain is not determining the right IP address. This usually occurs due to incorrect DNS records being set at the Domain hosting level. In case you have the correct DNS records set, you also have to keep in mind that changes in DNS can take time to propagate globally. This relies on various factors including time to live or TTL.
3. Block Request By Firewall:
The firewall is used to block the transmission between the servers. It is another common reason to face the 502 error. There is the possibility that your WordPress security plugins might block the communication between the servers or can even block your local or ISP IP. To rule this out, you can try accessing the site from a different Internet connection. Moreover, few DDOS protection systems are over-sensitive that start blocking the requests from servers.
4. Failure of the Server:
You might experience a 502 error if the server has completely failed. It can be due to a system crash or sometimes the server is taken offline for maintenance or similar reasons. This can also be because the content of the server might be violating the server provider’s terms and conditions.
5. Error in Browser:
Sometimes, some browser extensions can also lead to errors while rendering the website, particularly AdBlock extensions. Apart from this, there might be rare cases that might cause the error due to the browser version being outdated.
How To Fix The 502 Bad Gateway Error?
There are numerous things that you can try to resolve this problem. Mostly, the 502 errors are the result of bugs in the PHP or the Server configuration or network error among servers. There is nothing wrong with your computer or your internet connectivity.
Nonetheless, in some cases, there might be a problem at your end with the browser, or your ISP or local IP might be blocked as mentioned earlier above. With these fixes, you can try and resolve the 502 error.
Common Fixes for 502 Bad Gateway Error (For Users):
Refresh the webpage
When experiencing a 502 error, there are chances that the server of the website might be overloaded with a higher amount of traffic than it cannot handle. If this is the case, you can try to fix this by simply refreshing the webpage.
Alternatively, you can also press the keys Ctrl + R or F5 to refresh/reload the page. This error means there is a networking error that is beyond your control, so it can be a temporary error while the server is getting a large amount of traffic or the server could be under a DDOS attack. By trying again in a while, you might not see this again.
Try in Incognito Mode
Another way to fix this error is by starting a new Private or Incognito session in your browser. All you have to do is just close the existing tabs and open a new Private or Incognito window. If you experienced this error because of an issue on your browser, then starting your browser again in the Private mode should resolve the issue.
Clear Cache Memory of your Browser
There is a chance that the corrupted files stored on your browser might be causing a 502 bad gateway error. So, if you clear the cache of your browser, you might resolve this error. Moreover, you should remove the cookies from your browser. It can also help in resolving this error.
Try Another Browser
You can try to use another browser such as Chrome, Safari, Firefox, and Internet Explorer. If you don’t see this error when you change your browser, this indicates that the problem was in the browser. You can even reinstall the browser to check if this resolves the problem.
Check Your DNS
Another solution for this error is by checking your domains’ DNS records. Sometimes the Bad Gateway error is caused by problems associated with DNS records. If you have not changed the DNS records, then you can also check if the IP in the records is set correctly and there is no typo there.
Restart Your Network Device
First of all, You need to switch off the power supply of your internet modem. To do this, Unplug your internet modem and hold it up for 10 seconds. When its indicators are completely turned off, You need to plug it in again and turn on the power on button and Wait for your computer to establish a connection again.
Common Fixes for 502 Bad Gateway Error (Developers):
If you are a developer or a server manager and you are facing this error, there are chances that you might be facing this error because of other factors. You can try these solutions for eliminating the problem.
By doing this you will get all the information regarding the errors that have occurred due to any recently added application. And you will get all the causes of the errors which are produced by your website.
Summary
As you can see from the above post, there are sufficient methods available combining both user and developer-friendly available, With the help of which you can do troubleshoot and try to fix a 502 bad gateway error on your WordPress site.
Since this error triggers from the server-side rather than the client-side. It means the problem is not coming from either your website, computer, or internet connection. However, you should not forget to check out your third-party plugins or themes for bad codes or misconfigured files.
We hope, the methods mentioned in this post to fix 502 bad gateway errors will help you to bring your website normal just like it was before the error. If you have any more methods or solutions, that we haven’t covered in this post, feel free to let us know in the comment section below.
General FAQ
How do I fix Error 502?
You can fix Error 502 by doing the following methods:
Refresh your browser and reopen it: First, you need to close your current browser and hold up a couple of moments and reopen it. It is because Sometimes your browser may stop responding due to accessing the heavy traffic of data at the same time or maybe an error page is inserted in between the pages which are loading. Even you try on another browser as well.
Reset Internet configuration: You need to restart your internet modem. to do this, Unplug your internet modem and hold it up for 5 seconds, after it completely turns off, Plugs it in again and Wait for your computer to establish a connection again.
Disable CDN temporarily: The Content Delivery Network or commonly known as CDN improves the loading speed of a website but it can generate error 502 as well due to the firewalls. To overcome this issue, you can disable the CDN temporarily.
What does a 502 error mean?
Error 502 is an Html status code that defines The server works as a passage or proxy and got a not valid response from the server. It is classified as a server error. This kind of error shows a communication problem between the two servers. It happens when the user PC interfaces with a server that works as a gateway or as a proxy and that requirements to get to a server that is in a higher hierarchy and that gives extra support.
What causes 502 Bad Gateway Nginx?
A 502 error happens when one web server gets a response that is not valid from another web server. The servers that communicate do not agree on the protocol for exchanging information. This sort of error is normally for a short period, so we can later attempt to enter the web once more. More often, the issue is on the website itself, and there’s very little you can do. But, this 502 Bad Gateway Nginx error can happen due to an issue on your PC or your internet hotspot device.
Following are some reasons:
1. Browser configuration problem
2. Server overloaded
3. not correctly configured servers
4. Error in communication between two servers
What causes a 502 Bad Gateway error?
Error 502 or commonly known as 502 bad gateway can also be due to problems at the server-side or Website itself. On account of error 502, It is also possible that Your system or PC configuration doesn’t match with the network standards, which can be assumed if the code shows up when attempting to open any page.
Causes of Error 502
1. Errors in PHP programming
2. Servers Overloaded
3. Browser problems
4. Communication problem between two servers
5. Server Crash
Does 502 bad gateway mean blocked?
If your computer screen displays an error message stating “502 bad gateway”, it means the server which is acting as a proxy or gateway is not getting adequate response from another server. But this is a generic error, you won’t be able to find out the root cause.
So, one can’t say, whether it is blocked or not without conducting any further investigation.
Unable to start process C:\Program Files\dotnet\dotnet.exe. The web server request failed with status code 502. Error in Visual Studio 2017
I am facing a strange issue while building a solution which has web projects. I get the error below. Any solution or thought on it.
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Fixed by adding forwardWindowsAuthToken=»false» in the web.config file.
I faced the same issue here
How I fix
(1) Open Event Log. I noticed that there is a warning: ‘Static compression is being disabled‘.
(2) Follow the 2 links to fix this issue
Enable ‘Use the 64 bit version of IIS Express for web sites and projects’ (My system is 64 bit)
I am not very sure what happen exactly. But this helps me to fix this issue. Hope it can help you as well.
502 bad gateway error explained: What it is and how to fix it
Aug 28, 2020 — 3 min read
Find out what it is, what causes it and how to fix it
Internet error messages are hugely confusing, with strange codes impossible for the average user to understand.
But don’t panic, we’re to explain exactly what a 502 error is, and what you can do if you see one.
Every time you plug in a URL, that request goes through a gateway.
In the case of a 502 bad gateway error, the server acting as the gateway, or proxy, received an invalid response from the main server that’s upstream.
In other words, there’s been a communication breakdown. While it’s out of your hands for the most part, there are a few things you can try to resolve the issue.
A 502 Bad Gateway error isn’t as bad as it sounds
A 502 error is one of many HTTP status codes and it’s also fairly common. You might also see it show up as:
Reasons you may be getting a 502 error
There are a handful of possibilities as to why the 502 error message is appearing on the website you’re trying to access.
6 ways to troubleshoot a 502 error message
Most often, a 502 bad gateway error has nothing to do with you as a visitor to the site. There are, however, a few things you can try just to be sure it’s not something on your side. Try these troubleshooting ideas in order because you might fix the issue faster than expected.
Other 500 error codes
Anytime you see an error message beginning with “5” that means the server isn’t able to perform the request. In addition to a 502 bad gateway error, you might also see:
как исправить ошибку 502 bad gateway
Ошибка 502 bad gateway: что значит и как исправить:
Во время серфинга по интернету и обращения к различным узлам иногда в браузере может появиться следующее сообщение об ошибке 502 Bad Gateway. При этом страницы сайта не открываются и нет возможности изучить ресурсы данного веб-узла. Обычна данная ошибка возникает в следствии проблем в работе серверов: прокси, DNS или хостинг-сервера, на котором находится недоступный в данный момент сайт сайт.
Ошибка 502 Bad Gateway переводится как «Неверный шлюз» и означает то, что обозреватель интернета (браузер) на вашем компьютере при запросе информации с веб-узла получил недопустимый ответ от сервера или DNS сервера, о чем и сообщает пользователю.
Что же можно предпринять в данном случае?
1. Проверить имеется ли вообще доступ к ресурсам сети Интренет. Для этого наберите в браузере наберите адрес любого другого сайта, желательно гарантированно работающего.
Ошибка 502 bad gateway: что значит и как исправить:
Во время серфинга по интернету и обращения к различным узлам иногда в браузере может появиться следующее сообщение об ошибке 502 Bad Gateway. При этом страницы сайта не открываются и нет возможности изучить ресурсы данного веб-узла. Обычна данная ошибка возникает в следствии проблем в работе серверов: прокси, DNS или хостинг-сервера, на котором находится недоступный в данный момент сайт сайт.
Ошибка 502 Bad Gateway переводится как «Неверный шлюз» и означает то, что обозреватель интернета (браузер) на вашем компьютере при запросе информации с веб-узла получил недопустимый ответ от сервера или DNS сервера, о чем и сообщает пользователю.
Что же можно предпринять в данном случае?
1. Проверить имеется ли вообще доступ к ресурсам сети Интренет. Для этого наберите в браузере наберите адрес любого другого сайта, желательно гарантированно работающего.
Error Request failed with status code 502 #128
Comments
varundeva commented Jun 5, 2020 •
Why Showing Error
Request failed with status code 502 when i send campaign? i first tried to send test. it showing error
hosted on heroku
using amazon SES SMTP
added config var by seeing doc
2020-06-05T07:31:09.196340+00:00 heroku[router]: at=info method=POST path=»/api/campaigns/3/test» host=bunews.herokuapp.com request_id=2fb16e4b-dc6f-454c-8df9-8a8c967d16c1 fwd=»103.89.232.28″ dyno=web.1 connect=0ms service=7ms status=502 bytes=295 protocol=https
The text was updated successfully, but these errors were encountered:
knadh commented Jun 5, 2020
502 happens when a service is not running. Maybe listmonk crashed? You should look at the app logs.
varundeva commented Jun 5, 2020
I’ve checked
See log is attached
Only that much log coming
I installed by using heroku deploy button
Manually added smtp variables
varundeva commented Jun 5, 2020
mr-karan commented Jun 5, 2020
Ah, can you please show a list of all SMTP related env keys you added (with their actual values redacted?)
The stack trace seem to indicate this is the issue, but runtime config will be helpful to drill down.
varundeva commented Jun 5, 2020
Ah, can you please show a list of all SMTP related env keys you added (with their actual values redacted?)
The stack trace seem to indicate this is the issue, but runtime config will be helpful to drill down.
image upload
knadh commented Jun 5, 2020
This happens when no SMTP configuration is found in the config. Ideally, it shouldn’t crash (just added a check for that 3048ab5)
I’m not familiar with the Heroku environment, but listmonk isn’t receiving SMTP config.
varundeva commented Jun 5, 2020
This happens when no SMTP configuration is found in the config. Ideally, it shouldn’t crash (just added a check for that 3048ab5)
I’m not familiar with the Heroku environment, but listmonk isn’t receiving SMTP config.
Ok then need to add all variables there? i left additional smtp using details only.
Can you just say which are the mandatory env variables?
mr-karan commented Jun 5, 2020
@knadh Can confirm, that is indeed the issue. e.numServers is 0 when none of the servers are read and the panic happens in here (the logs were a bit confusing, but I was able to replicate it correctly on my local config. 3048ab5 fixed it 👍 )
@varundeva Not that it should cause this, but I spotted a typo in your env config:
Can you please confirm somehow, that the values you’ve shown here are indeed present inside Heroku’s env?
Additionally, also run with the latest commit and you will see a helpful error message indicating that no SMTP servers are being read, which will also tell you that env variables are a problem with your setup
varundeva commented Jun 5, 2020
@knadh Can confirm, that is indeed the issue. e.numServers is 0 when none of the servers are read and the panic happens in here (the logs were a bit confusing, but I was able to replicate it correctly on my local config. 3048ab5 fixed it )
@varundeva Not that it should cause this, but I spotted a typo in your env config:
Can you please confirm somehow, that the values you’ve shown here are indeed present inside Heroku’s env?
Additionally, also run with the latest commit and you will see a helpful error message indicating that no SMTP servers are being read, which will also tell you that env variables are a problem with your setup
Request failed with status code 502 #1164
Comments
eravindar12 commented Sep 11, 2019
I am facing an issue with kubeapps, after i login seeing this error.
Please advice.
Sorry! Something went wrong.
Request failed with status code 502
Troubleshooting:
The text was updated successfully, but these errors were encountered:
andresmgot commented Sep 12, 2019
What’s in your browser console? How did you deploy Kubeapps?
andresmgot commented Oct 8, 2019
@eravindar12 I am going to close this ticket due to inactivity. If you still find problems please let us know and reopen this issue.
camgab commented Oct 23, 2019
I have the same problem every time I try to deploy an application for example in my case It was an Nginx Ingress that I want to deploy.
andresmgot commented Oct 23, 2019
Can you let us know which version of Kubeapps you are running and how are you accessing the application (e.g. with an ingress or doing a port-forward)?
Also, can you let us know any additional info that you can get from the developer console? Like the error in the console or the request that is returning the 502.
camgab commented Oct 23, 2019 •
Version of kubeapps is 1.6.0. Chart version of Nginx-ingress is 1.24.3
Im accessing the application with an ingress. I even didn’t make any change in the YAML and have also errors.
I have errors below in the console.
Failed to load resource: the server responded with a status of 401 ()
andresmgot commented Oct 24, 2019
What’s the difference between the deployments? How do you deploy it without using the command line?
ybabel commented Dec 3, 2019
Same problem here. I’m new to kubernetes/helm.
I have access to the dashboard but got a 502.
I’m using microk8s on ubuntu server 18.04
On the dashboard I can see kubeapps deployed and running.
andresmgot commented Dec 3, 2019
ybabel commented Dec 3, 2019 •
thank you for help.
Here is my pods :
I noticed many of them seem’s to be duplicated, but I don’t know if its normal or not.
On my network tab, everything is 200 except a 502 at
http://192.168.0.37:8080/api/tiller-deploy/v1/namespaces/default/releases
Error 502 Bad Gateway: Where’s the problem?
Everything doesn’t always run smoothly when surfing the net. Now and again, you’ll visit a website and instead be greeted by an HTTP status code. Something went wrong! If you run up against a 500 code as an internet user, then in most cases the problem is not with you or your internet connection — it’s far more likely that it’s the website’s server instead. With a 502 error, though, it can occasionally happen that something is wrong with your settings — especially if you’re suddenly receiving the annoying status code regardless of which sites you’re trying to access. This article gives you tips on how to suss out the source of the error and what you can do as a user to once again view the content of the website. Or are you the operator of an affected website? We’ll tell you how to check for that error too.
What does ‘bad gateway’ mean?
The internet protocol HTTP generally provides status codes in response to queries. The most common code is probably number 200: OK. Everything has worked as it should. This status isn’t usually shown to users, though. Instead, visitors simply see the requested website content. On the flip side are the error messages: While 400 codes imply that the error lies on the client side, 500 to 511 codes mean that the negative result is the server’s fault. The status codes also indicate where the error occurred — at least to users who know what the individual codes 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.
What are the sources of the 502 Bad Gateway error?
In most cases, the bad gateway error occurs on the server side and can’t be fixed by the internet user. But it’s also possible that the browser being used has registered a 502 error where really none exists. It’s also possible that you’re disconnected from your network. The following reasons could explain why the infamous HTTP code is displayed:
Fixing the 502 error
Internet users, as well as webmasters, have the ability to respond to a bad gateway situation. In many cases, just waiting for a little while is enough. Often, the error occurs outside of your sphere of influence and is solved by the internet provider (ISP) or the hosting provider of the web server without any intervention on your part. But sometimes the error is on your side, so you should know where to begin to search for the cause.
As an internet user: Fix 502 or bypass it
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.)
If the error is actually on the server side but you still want to access the content right away, there are also other ways to bypass the error message. This relies on the Google cache. Google saves websites for a time on its own servers and so can display an earlier version of the respective website. To load the cache page of the search engine, enter cache: in the search field and then the URL that you would like to visit (for example, cache:https://facebook.com). You should be aware, though, that you’re viewing an outdated version of the site. If you need to go back through the site’s history to find a working version, then the Wayback machine — from the nonprofit internet archive — can help. Various versions from the past years are stored here.
If you load a website from the Google cache, it provides a panel to inform you of when the copy was created.
The error could also be in your system — even if the status code indicates something else. To check whether the error stems from other users or you, you can, for example, use the web service Down for everyone or just me?. Of course, if you can’t access any websites without the “Bad Gateway” message, then it’s obvious that the error has something to do with your computer, browser, or firewall. If the error is actually only occurring for you, then check the functionality of your browser. The first step should be restarting the browser. If this doesn’t work, then start your browser in safe mode. In safe mode, the browser deactivates any installed plugins. This allows you to check if a browser extension is the source of the error message.
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:
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.
As a webmaster: Examine the website
A visitor to your website has shared with you that they’re seeing the error message 502 when they try to access your website. What does that mean for you? Just as for the surfing visitor, it’s not always clear to the webmaster at first glance where the error lies. First, you need to check whether your website is still accessible in general. If your server is truly failing, you should contact your hosting provider. Maybe they already know about the error and their IT team is working on a solution. You should also check the log files of your server for error messages. PHP programming in particular can often be the source of errors, so definitely check if your error source is either there or in your database. If necessary, you could use an old backup to quickly remedy the failure.
Oftentimes, the error only occurs because the server was temporarily overloaded or took too long to provide a response to the upstream server. If such overloads start occurring more frequently, you should contact your hosting provider. Together, you can achieve a better configuration for your webserver so that it doesn’t fall to its knees at peak times. But in some cases, it’s the communication between the different webservers that isn’t running smoothly. Then you should check whether your firewall is correctly set up and make sure that it’s not blocking any legitimate queries. Another source of error could be that the name resolution isn’t functioning properly. Check your name server settings with your hosting provider (for IONOS users, this takes place via the customer login. There you need to select the appropriate domain and switch to DNS settings).
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.
что за ошибка 502
При просмотре Интернета и повторном обращении к одним и тем же ссылкам иногда может появляться сообщение: 502 Bad Gateway. Пользователь при этом не имеет возможности просмотра ресурсов выбранного Web-сайта. Обычно такое сообщение является следствием проблем, касающихся работы прокси-сервера, DNS-сервера или хостинг-сервера, где непосредственно размещается Web-сайт, который запрашивает пользователь.
С формальной точки зрения получение названного сообщения означает, что ваш браузер получил недопустимый ответ от другого сервера (или прокси-сервера) и выводит общую заставку «502 Bad Gateway», для информирования о возникшей ситуации.
Что же в таких случаях можно предпринять?
При просмотре Интернета и повторном обращении к одним и тем же ссылкам иногда может появляться сообщение: 502 Bad Gateway. Пользователь при этом не имеет возможности просмотра ресурсов выбранного Web-сайта. Обычно такое сообщение является следствием проблем, касающихся работы прокси-сервера, DNS-сервера или хостинг-сервера, где непосредственно размещается Web-сайт, который запрашивает пользователь.
С формальной точки зрения получение названного сообщения означает, что ваш браузер получил недопустимый ответ от другого сервера (или прокси-сервера) и выводит общую заставку «502 Bad Gateway», для информирования о возникшей ситуации.
Что же в таких случаях можно предпринять?
Ошибка 502 bad gateway: что значит и как исправить:
Во время серфинга по интернету и обращения к различным узлам иногда в браузере может появиться следующее сообщение об ошибке 502 Bad Gateway. При этом страницы сайта не открываются и нет возможности изучить ресурсы данного веб-узла. Обычна данная ошибка возникает в следствии проблем в работе серверов: прокси, DNS или хостинг-сервера, на котором находится недоступный в данный момент сайт сайт.
Ошибка 502 Bad Gateway переводится как «Неверный шлюз» и означает то, что обозреватель интернета (браузер) на вашем компьютере при запросе информации с веб-узла получил недопустимый ответ от сервера или DNS сервера, о чем и сообщает пользователю.
Что же можно предпринять в данном случае?
1. Проверить имеется ли вообще доступ к ресурсам сети Интренет. Для этого наберите в браузере наберите адрес любого другого сайта, желательно гарантированно работающего.
Should a 502 HTTP status code be used if a proxy receives no response at all?
According to the RFC:
10.5.3 502 Bad Gateway
The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.
Can invalid response also mean no response at all (e.g. connection refused)?
1 Answer 1
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
Not the answer you’re looking for? Browse other questions tagged http client http-status-codes status or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Единый форум поддержки
Меню навигации
Пользовательские ссылки
Информация о пользователе
Вы здесь » Единый форум поддержки » Справочная » Расшифровка кодов ошибок (502) ответа HTTP сервера
Расшифровка кодов ошибок (502) ответа HTTP сервера
Сообщений 1 страница 3 из 3
Поделиться1Чт, 15 Май 2008 09:24:18
Все коды ответов HTTP сервера:
100 Продолжение
101 Переключение протоколов
200 Норма
201 Принят
202 Создан
203 Не авторитетная информация
204 Не содержит
205 Сбросить содержание
206 Частично содержит
300 Множественный выбор
301 Перемещен постоянно
302 Перемещен временно
303 Смотри другой
304 Не изменен
305 Используй посредника
400 Неверный запрос
401 Неизвестен
402 Необходима оплата
403 Запретный
404 Не найден
405 Метод не может быть разрешен
406 Не доступен
407 Требуется идентификация прокси, файервола
408 Тайм-аут запроса
409 Конфликт
410 Послан
411 Необходима длина
412 Предварительная ошибка
413 Тело запроса слишком велико
414 URI запроса слишком велико
415 Неподдерживаемый тип медиатипов
416 Не применим
500 Внутренняя ошибка сервера
501 Не выполнено
502 Ошибка межсетевого шлюза
503 Служба не доступна
504 Тайм-аут межсетевого шлюза
505 Версия НТТР не поддерживается
Отредактировано Lexx (Чт, 15 Май 2008 09:24:53)
Поделиться2Чт, 15 Май 2008 09:25:57
Дополнительная документация по Parser http://www.parser.ru/docs/lang/
В большинстве своем ошибка случается по вине парсера, когда ошибка исходит от сервера в остальномм ошибка клиента тоесть подсоединения по интернету может быть недостаточным тут играет роль не только скрость подключения, но и мощность компьютера, а также свободность канала причем в некотрых случа с двух сторон.
Отредактировано Lexx (Чт, 15 Май 2008 09:44:13)
Поделиться3Чт, 15 Май 2008 09:36:30
Ошибки передачи данных.
При запросе документов нередко происходят ошибки передачи данных. Что из них можно узнать? По коду полученного ответа сервера можно понять, на чьей стороне она возникла и ее причины.
На каждый запрос пользователя сервер отвечает попытокой передачи данных в определенной последовательности и формате. Например, HTTP-ответ (Response) имеет следующий формат:
Код ответа является трехзначным числом. Коды разделены по группам в зависимости от первой цифры:
1xx Промежуточные информационные сообщения (практически не используется).
2xx Успешная обработка запроса.
Примеры:
4xx Ошибка клиента.
Примеры:
5xx Ошибка сервера.
Примеры:
Вот еще некоторые варианты.
А ВОТ ОРИГИНАЛ )))
Status Code Definitions
RFC 2616 HTTP/1.1 June 1999
Each Status-Code is described below, including a description of which method(s) it can follow and any metainformation required in the response.
This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. There are no required headers for this class of status code. Since HTTP/1.0 did not define any 1xx status codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client except under experimental conditions.
A client MUST be prepared to accept one or more 1xx status responses prior to a regular response, even if the client does not expect a 100 (Continue) status message. Unexpected 1xx status responses MAY be ignored by a user agent.
Proxies MUST forward 1xx responses, unless the connection between the proxy and its client has been closed, or unless the proxy itself requested the generation of the 1xx response. (For example, if a proxy adds a «Expect: 100-continue» field when it forwards a request, then it need not forward the corresponding 100 (Continue) response(s).)
The client SHOULD continue with its request. This interim response is used to inform the client that the initial part of the request has been received and has not yet been rejected by the server. The client SHOULD continue by sending the remainder of the request or, if the request has already been completed, ignore this response. The server MUST send a final response after the request has been completed. See section 8.2.3 for detailed discussion of the use and handling of this status code.
101 Switching Protocols
The server understands and is willing to comply with the client’s request, via the Upgrade message header field (section 14.42), for a change in the application protocol being used on this connection. The server will switch protocols to those defined by the response’s Upgrade header field immediately after the empty line which terminates the 101 response.
The protocol SHOULD be switched only when it is advantageous to do so. For example, switching to a newer version of HTTP is advantageous over older versions, and switching to a real-time, synchronous protocol might be advantageous when delivering resources that use such features.
This class of status code indicates that the client’s request was successfully received, understood, and accepted.
The request has succeeded. The information returned with the response is dependent on the method used in the request, for example:
GET an entity corresponding to the requested resource is sent in the response;
HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;
POST an entity describing or containing the result of the action;
TRACE an entity containing the request message as received by the end server.
The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.
A 201 response MAY contain an ETag response header field indicating the current value of the entity tag for the requested variant just created, see section 14.19.
The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this.
The 202 response is intentionally non-committal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent’s connection to the server persist until the process is completed. The entity returned with this response SHOULD include an indication of the request’s current status and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled.
203 Non-Authoritative Information
The returned metainformation in the entity-header is not the definitive set as available from the origin server, but is gathered from a local or a third-party copy. The set presented MAY be a subset or superset of the original version. For example, including local annotation information about the resource might result in a superset of the metainformation known by the origin server. Use of this response code is not required and is only appropriate when the response would otherwise be 200 (OK).
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent’s active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent’s active view.
The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.
205 Reset Content
The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent. This response is primarily intended to allow input for actions to take place via user input, followed by a clearing of the form in which the input is given so that the user can easily initiate another input action. The response MUST NOT include an entity.
206 Partial Content
The server has fulfilled the partial GET request for the resource. The request MUST have included a Range header field (section 14.35) indicating the desired range, and MAY have included an If-Range header field (section 14.27) to make the request conditional.
The response MUST include the following header fields:
— Either a Content-Range header field (section 14.16) indicating the range included with this response, or a multipart/byteranges Content-Type including Content-Range fields for each part. If a Content-Length header field is present in the response, its value MUST match the actual number of OCTETs transmitted in the message-body.
— ETag and/or Content-Location, if the header would have been sent in a 200 response to the same request
— Expires, Cache-Control, and/or Vary, if the field-value might differ from that sent in any previous response for the same variant
If the 206 response is the result of an If-Range request that used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. If the response is the result of an If-Range request that used a weak validator, the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers. Otherwise, the response MUST include all of the entity-headers that would have been returned with a 200 (OK) response to the same request.
A cache MUST NOT combine a 206 response with other previously cached content if the ETag or Last-Modified headers do not match exactly, see 13.5.4.
A cache that does not support the Range and Content-Range headers MUST NOT cache 206 (Partial) responses.
This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. A client SHOULD detect infinite redirection loops, since such loops generate network traffic for each redirection.
Note: previous versions of this specification recommended a maximum of five redirections. Content developers should be aware that there might be clients that implement such a fixed limitation.
300 Multiple Choices
The requested resource corresponds to any one of a set of representations, each with its own specific location, and agent- driven negotiation information (section 12) is being provided so that the user (or user agent) can select a preferred representation and redirect its request to that location.
Unless it was a HEAD request, the response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content- Type header field. Depending upon the format and the capabilities of
the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.
If the server has a preferred choice of representation, it SHOULD include the specific URI for that representation in the Location field; user agents MAY use the Location field value for automatic redirection. This response is cacheable unless indicated otherwise.
301 Moved Permanently
The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.
The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).
If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.
The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.
The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).
If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.
The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.
The different URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).
Note: Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.
304 Not Modified
If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.
The response MUST include the following header fields:
— Date, unless its omission is required by section 14.18.1
If a clockless origin server obeys these rules, and proxies and clients add their own Date to any response received without one (as already specified by [RFC 2068], section 14.19), caches will operate correctly.
— ETag and/or Content-Location, if the header would have been sent in a 200 response to the same request
— Expires, Cache-Control, and/or Vary, if the field-value might differ from that sent in any previous response for the same variant
If the conditional GET used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. Otherwise (i.e., the conditional GET used a weak validator), the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers.
If a 304 response indicates an entity not currently cached, then the cache MUST disregard the response and repeat the request without the conditional.
If a cache uses a received 304 response to update a cache entry, the cache MUST update the entry to reflect any new field values given in the response.
The requested resource MUST be accessed through the proxy given by the Location field. The Location field gives the URI of the proxy. The recipient is expected to repeat this single request via the proxy. 305 responses MUST only be generated by origin servers.
Note: RFC 2068 was not clear that 305 was intended to redirect a single request, and to be generated by origin servers only. Not observing these limitations has significant security consequences.
The 306 status code was used in a previous version of the specification, is no longer used, and the code is reserved.
307 Temporary Redirect
The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.
If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
Client Error 4xx
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included entity to the user.
If the client is sending data, a server implementation using TCP SHOULD be careful to ensure that the client acknowledges receipt of the packet(s) containing the response, before the server closes the input connection. If the client continues sending data to the server after the close, the server’s TCP stack will send a reset packet to the client, which may erase the client’s unacknowledged input buffers before they can be read and interpreted by the HTTP application.
400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in «HTTP Authentication: Basic and Digest Access Authentication» [43].
402 Payment Required
This code is reserved for future use.
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.
406 Not Acceptable
The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.
Unless it was a HEAD request, the response SHOULD include an entity containing a list of available entity characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. Depending upon the format and the capabilities of the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.
Note: HTTP/1.1 servers are allowed to return responses which are not acceptable according to the accept headers sent in the request. In some cases, this may even be preferable to sending a 406 response. User agents are encouraged to inspect the headers of an incoming response to determine if it is acceptable.
If the response could be unacceptable, a user agent SHOULD temporarily stop receipt of more data and query the user for a decision on further actions.
407 Proxy Authentication Required
This code is similar to 401 (Unauthorized), but indicates that the client must first authenticate itself with the proxy. The proxy MUST return a Proxy-Authenticate header field (section 14.33) containing a challenge applicable to the proxy for the requested resource. The client MAY repeat the request with a suitable Proxy-Authorization header field (section 14.34). HTTP access authentication is explained in «HTTP Authentication: Basic and Digest Access Authentication» [43].
408 Request Timeout
The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough
information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can’t complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
The requested resource is no longer available at the server and no forwarding address is known. This condition is expected to be considered permanent. Clients with link editing capabilities SHOULD delete references to the Request-URI after user approval. If the server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) SHOULD be used instead. This response is cacheable unless indicated otherwise.
411 Length Required
The server refuses to accept the request without a defined Content- Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message.
412 Precondition Failed
The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. This response code allows the client to place preconditions on the current resource metainformation (header field data) and thus prevent the requested method from being applied to a resource other than the one intended.
413 Request Entity Too Large
The server is refusing to process a request because the request entity is larger than the server is willing or able to process. The server MAY close the connection to prevent the client from continuing the request.
If the condition is temporary, the server SHOULD include a Retry- After header field to indicate that it is temporary and after what time the client MAY try again.
414 Request-URI Too Long
The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret. This rare condition is only likely to occur when a client has improperly converted a POST request to a GET request with long query information, when the client has descended into a URI «black hole» of redirection (e.g., a redirected URI prefix that points to a suffix of itself), or when the server is under attack by a client attempting to exploit security holes present in some servers using fixed-length buffers for reading or manipulating the Request-URI.
415 Unsupported Media Type
The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.
416 Requested Range Not Satisfiable
A server SHOULD return a response with this status code if a request included a Range request-header field (section 14.35), and none of the range-specifier values in this field overlap the current extent of the selected resource, and the request did not include an If-Range request-header field. (For byte-ranges, this means that the first- byte-pos of all of the byte-range-spec values were greater than the current length of the selected resource.)
When this status code is returned for a byte-range request, the response SHOULD include a Content-Range entity-header field specifying the current length of the selected resource (see section 14.16). This response MUST NOT use the multipart/byteranges content- type.
417 Expectation Failed
The expectation given in an Expect request-header field (see section 14.20) could not be met by this server, or, if the server is a proxy, the server has unambiguous evidence that the request could not be met by the next-hop server.
Server Error 5xx
Response status codes beginning with the digit «5» indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. User agents SHOULD display any included entity to the user. These response codes are applicable to any request method.
500 Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request.
501 Not Implemented
The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.
502 Bad Gateway
The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.
503 Service Unavailable
The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.
Note: The existence of the 503 status code does not imply that a server must use it when becoming overloaded. Some servers may wish to simply refuse the connection.
504 Gateway Timeout
The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request.
Note: Note to implementors: some deployed proxies are known to return 400 or 500 when DNS lookups time out.
505 HTTP Version Not Supported
The server does not support, or refuses to support, the HTTP protocol version that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client, as described in section 3.1, other than with this error message. The response SHOULD contain an entity describing why that version is not supported and what other protocols are supported by that server.
Отредактировано Lexx (Чт, 15 Май 2008 09:40:14)
nginx docker container: 502 bad gateway response
I’ve a service listening to 8080 port. This one is not a container.
Then, I’ve created a nginx container using official image:
Nginx configuration is:
I’ve checked I’m able to connect with with this server with # curl http://127.0.0.1:8080
It seems running well, however, when I’m trying to access using my browser, nginx tells bt a 502 bad gateway response.
I’m figuring out it can be a problem related with the visibility between a open by a non-containerized process and a container. Can I container stablish connection to a port open by other non-container process?
EDIT
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The Problem
Localhost is a bit tricky when it comes to containers. Within a docker container, localhost points to the container itself. This means, with an upstream like this:
you are telling nginx to pass your request to the local host. But in the context of a docker-container, localhost (and the corresponding ip addresses) are pointing to the container itself:
by addressing 127.0.0.1 you will never reach your host machine, if your container is not on the host network.
Solutions
Host Networking
You can choose to run nginx on the same network as your host:
Note that you do not need to expose any ports in this case.
This works though you lose the benefit of docker networking. If you have multiple containers that should communicate through the docker network, this approach can be a problem. If you just want to deploy nginx with docker and do not want to use any advanced docker network features, this approach is fine.
Access the hosts remote IP Address
Another approach is to reconfigure your nginx upstream directive to directly connect to your host machine by adding its remote IP address:
The container will now go through the network stack and resolve your host correctly:
You can also use your DNS name if you have one. Make sure docker knows about your DNS server.
Just to complete other answers, I’m using mac for development and using host.docker.internal directly on upstream worked for me and no need to pass the host remote IP address. Here is config of the proxy nginx:
As you can see, I used different ports for different apps behind the nginx proxy. I used port 81 for the app1 and port 82 for the app2 and both app1 and app2 have their own nginx containers:
Also, please refer to this link for more details: docker doc for mac
What you can do is configure proxy_pass that from container perspective the adress will be pointing to your real host.
To get host address from container perspective you can do as following on Windows with docker 18.03 (or more recent):
Run bash on container from host where image name is nginx (works on Alpine Linux distribution ):
Then run inside container
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker for Windows.
Then you can change nginx config to: proxy_pass http://192.168.65.2:
and it should work fine.
Remember to provide the same port as your local application runs with.
Support
Find answers, guides, and tutorials to supercharge your content delivery.
How to Solve 502 Bad Gateway Issues?
If you browse the internet long enough, you’ll run into a 502 Bad Gateway error code. This is especially true if you frequently visit websites known to be unreliable. While the error can be frustrating, the good news is that it’s usually easy to fix.
In this article, we’ll take a look at what a 502 Bad Gateway error code is and how you can go about solving it on your own.
What does 502 Bad Gateway mean?
A 502 Bad Gateway indicates that the edge server (server acting as a proxy) could not get a valid or any response from the origin server (also called the upstream server). This can occur for a few reasons, which we’ll discuss below. If one of KeyCDN’s edge servers receives a 502 Bad Gateway response from your origin server, KeyCDN will return a 500 Origin Not Reachable page.
To better understand how KeyCDN handles certain error codes, check out our CDN Error Codes page.
Usually, a 502 Bad Gateway error code is accompanied by a message letting you know that a «bad gateway» exists. In other words, something went wrong while the server was trying to relay information to another server (usually an upstream server). The most common cause of this issue is an incorrect or outdated DNS record.
What are the reasons for 502 Bad Gateway responses?
Three main culprits cause 502 Bad Gateway responses. These include:
How you might see a 502 Bad Gateway error
Based on your web server, you might see a different 502 error.
Every time, it means the same thing. The only different component is their naming conventions. Here are a few examples of what you might see:
How to solve 502 errors as a web developer
As a web developer or owner of the website, there are a few reasons why you may be experiencing a 502 Bad Gateway error on your origin server. Therefore, you may need to try various methods to resolve the issue. Reference the list of suggestions below:
How to solve 502 errors as a visitor
If you’re a website visitor and experience a 502 Bad Gateway error then there is also a few things you can try to resolve it. Although the primary issue will almost always be the responsibility of the web developer, visitors can try the following:
Common solutions for 502 Bad Gateway Error Code
Usually, a 502 error code is the result of a server error. A server error means that the server you are trying to access is unavailable or down. However, it is also possible on the client-side.
Here are some common ways to fix it in detail:
Reload the page
The first and easiest thing you can do is simply reload the page. A 502 error code and a 504 error code are both server-side errors. This means that there is something wrong with the server. The problem could be anything from the server being down to the server being too busy.
A reload will send a new request to the server. The server may be down, but it could also be that the original request timed out. A reload will often fix the problem.
Tools like DownForEveryoneOrJustMe are useful for seeing whether this is a server-side issue or an issue on your end.
Clear your browser’s cache
It is also possible that your browser’s cache is causing the problem. If you have recently visited the site, your browser may be trying to use an old version of the website. To clear your browser’s cache, go to the settings in your browser and look for the option to clear your cache.
In Google Chrome, you can go to the three dots in the top right corner and click More tools. From there, click Clear browsing data.
In Mozilla Firefox, you can go to the three bars in the top right corner and click Options. From there, click Privacy & Security and scroll down to Cookies and Site Data. Click Clear Data.
In Microsoft Edge, you can click the three dots in the top right corner and click Settings. From there, click Choose what to clear under Clear browsing data.
In Safari, you can click the Safari menu and click Preferences. From there, click the Privacy tab and click Manage Website Data. Click Remove All.
Restart your computer and router
It is also possible that the problem is on your end. If you have recently installed new software or made changes to your computer, these could be causing the problem. Try restarting your computer and see if that fixes the problem.
If the problem is on your end, one of your browser’s extensions is likely causing the problem. Try disabling all of your browser’s extensions and see if that fixes the problem.
If the problem is still not fixed, you can try resetting your router. To do this, unplug your router from the power outlet and wait 30 seconds. After 30 seconds, plug it back in and wait for it to connect to the internet.
Change your DNS servers
If you are still having problems, you can try changing your DNS servers. If you have never changed your DNS servers before, you likely have the default ones assigned to you by your ISP. If your DNS server is not responding or your domain is not resolving the correct IP, it can result in a 502 error.
However, you can try using public DNS servers such as Google’s Public DNS.
To change your DNS servers in Windows, go to the Control Panel and click Network and Sharing Center. From there, click Change adapter settings and double-click your internet connection.
Click Properties,then click the Networking tab. From there, double-click Internet Protocol Version 4 (TCP/IPv4).
In the General tab, click Use the following DNS server addresses. Enter 8.8.8.8 for the Preferred DNS server and 8.8.4.4 for the Alternate DNS server.
Click OK to save your changes.
You can also change your DNS servers in your router’s settings. The process will vary depending on your router, but you will likely be able to find the DNS settings in the Network or Internet section of the router’s settings.
Once you have changed your DNS servers, try loading the website again.
Flush DNS cache
DNS caching can also cause 502 errors. When you visit a website, your computer stores certain information about that site in its DNS cache. This can help your computer load the website faster the next time you visit it. However, if this information is outdated, it can result in a 502 error.
To flush your DNS cache, open the command prompt and enter the following:
Windows: ipconfig /flushdns
Linux: sudo /etc/init.d/networking force-reload
Once you have flushed your DNS cache, try loading the website again.
Temporarily disable Your CDN or firewall
Most servers use a content delivery network (CDN) such as KeyCDN. While very helpful (and important), these services can sometimes cause 502 errors. If you are using a CDN, try temporarily disabling it and see if that fixes the problem.
To disable your CDN in WordPress, go to the CDN tab in the Settings section of your WordPress dashboard and click the Disable CDN button. Click Save Changes.
In other CMSs, the process will be similar. Look for a CDN or Content Delivery Network settings page in your CMS’s dashboard and follow the instructions.
Similarly, your firewall could also be the cause of 502 errors. If you are using a firewall, try temporarily disabling it and see if that fixes the problem.
To do so, go to the Control Panel and click System and Security. From there, click Windows Firewall.
Click the Turn Windows Firewall on or off link in the left sidebar. If prompted for an administrator password or confirmation, enter the password or provide confirmation.
Click the Turn off Windows Firewall (not recommended) option for both private and public networks and click OK.
Summary
If you see 502 Bad Gateway errors, there are a few things you can do to try and fix the problem. Usually, this error code is an easy one to fix and requires one of the following:
If you are still having problems, you can try changing your DNS servers. If you have never changed your DNS servers before, you likely have your ISP’s DNS servers configured. However, you can try using public DNS servers such as Google’s Public DNS.
Worst case scenario, you will have to contact your ISP’s customer support. They should be able to help you troubleshoot the problem and get you back online.
Что означает ошибка сервера 503 и как ее исправить
Как и любая проблема с доступом к интернет-ресурсам, ошибка 503 Service Unavailable («Сервис недоступен») может быть вызвана сбоями как на стороне пользователя, так и на стороне сервера, на котором находится сайт. Поэтому первое, что нужно сделать, если вы столкнулись с таким сообщением при посещении веб-ресурса, попробовать устранить сбой своими силами. Это намного проще и быстрее, чем пытаться донести информацию о возникших сложностях до владельца сайта.
Процедура устранения проблемы со стороны администратора веб-ресурса более сложная, но в большинстве случаев именно неправильные настройки на уровне хостинга или настроек сайта в панели управления CMS приводят к появлению ошибки сервера с кодом 503.
Мощный хостинг в подарок при заказе лицензии 1С-Битрикс
Выбирайте надежную CMS с регулярными обновлениями системы и профессиональной поддержкой. А мы подарим вам год мощного хостинга – специально для сайтов на 1С-Битрикс.
Устранение ошибки 503 пользователем
Возникает резонный вопрос: почему бы просто не покинуть проблемный сайт, пусть сами разбираются со своими багами? Это решение очевидное, но не совсем верное. Во-первых, вам может быть очень необходимо посетить именно этот веб-ресурс. Во-вторых, появление сигнала об ошибке доступа может говорить о том, что с вашим браузером, программным обеспечением, компьютером или другими устройствами что-то не в порядке. И тогда это уже ваша проблема, которая может повторяться систематически и при посещении других сайтов. Рассмотрим, что можно сделать самому, чтобы исправить ошибку 503, двигаясь от простого к сложному.
Если ни один из вышеприведенных способов не помог, а достучаться до сайта ну очень нужно, пишите о проблеме в техподдержку данного ресурса, приложив скриншот страницы с кодом и описанием ошибки.
Ошибка 503 может отображаться в разных форматах с дополнительными информативными сообщениями. Появление страницы «503 Service Temporary Unavailable – Сервис временно недоступен» говорит о том, что проблема носит временный характер. В этом случае пользователю рекомендуется не предпринимать никаких действий и просто дождаться, когда доступ восстановится автоматически.
Решение проблем с ошибкой 503 администратором веб-ресурса
При возникновении ошибки 503 Service Unavailable в любом ее проявлении администратор web-ресурса в первую очередь должен разобраться в причине ее появления. Игнорирование данной процедуры по принципу «само пройдет» может привести к тому, что сайт понесет глобальные потери в объеме пользовательского трафика и, как следствие, конверсии. Посетители, регулярно сталкивающиеся с проблемами доступа к определенному ресурсу, очень быстро занесут его в «игнор».
В зависимости от конкретного тарифного плана хостинга каждый сайт имеет ограничения по одновременной обработке запросов, поступающих на сервер от конечных пользователей. Более простые запросы браузеров обрабатываются практически мгновенно, сложные ожидают очереди в порядке их поступления. Количество отложенных запросов лимитировано, при превышении нормы каждый следующий отклоняется. В этом случае посетитель сайта видит на экране сообщение с кодировкой error 503.
Наиболее частые причины возникновения ошибки 503 на стороне сервера
Как видим, решение практически всех проблем, приводящих к появлению ошибки 503, достигается использованием более мощных серверов и высокоскоростного качественного хостинга. Отрицательная сторона этого способа в его затратности. Распределение пользовательского трафика неравномерно по времени, и банальный апгрейд железа не поможет полностью исключить сбои в моменты пиковых нагрузок.
Как избежать появления ошибок 503
Для начала рекомендуется провести статистический анализ через административную панель (снять логи), чтобы понять, какие процессы создают максимальную нагрузку на сервер, и произвести определенные изменения в настройках.
Уменьшение нагрузки на базу данных можно добиться следующими способами:
Оптимизация работы скриптов
Дополнительную нагрузку на сервер, приводящую к появлению ошибки 503, могут создать DDoS-атаки. Защита от них с помощью фильтрации относится к отдельной теме обсуждения.
Следует отметить, что ошибка 503, вызванная перегрузкой серверных мощностей, может пройти сама собой, без внешнего вмешательства. Чтобы понять, произошло ли исправление ситуации, достаточно периодически перезагружать сайт.
Заключение
Ошибка 503 Service Unavailable может возникнуть на любом сайте, управляемом одной из наиболее популярных CMS – WordPress (Вордпресс), Joomla (Джумла), DLE (ДЛЕ) и любой другой, использующей базы данных MySQL. Способов ее решения много, начиная от самых простых на уровне пользователя и заканчивая довольно сложными процедурами, которые должен выполнить администратор сайта.
Буду благодарен, если вы нашли нестандартный подход к устранению сбоя с кодировкой 503 и готовы поделиться своим опытом в комментариях!
What is a 502 Bad Gateway Error (And How Can I Fix It)?
A 502 Bad Gateway Error occurs when you try to visit a web page, but one web server gets an invalid response from another. Normally, the problem is on the website itself, and there’s nothing you can do. Other times, this error occurs because of a problem with your computer or networking equipment.
What is a 502 Bad Gateway Error?
A 502 Bad Gateway Error means that the web server you’ve connected to is acting as a proxy for relaying information from another server, but it has gotten a bad response from that other server. It’s called a 502 error because that’s the HTTP status code that the webserver uses to describe that kind of error.
These bad responses could be due to a number of different causes. It’s possible the server is overloaded or there are network issues between the two servers, and it’s just a temporary problem. It’s also possible there’s an improperly configured firewall or even a coding error, and that the problem won’t get fixed until those issues are addressed.
Just like with 404 errors, website designers can customize how a 502 error looks. So, you might see different-looking 502 pages on different websites. Websites might also use slightly different names for this error. For example, you might see things like:
The vast majority of the time, this is just an error on the server-side of things that you won’t be able to do anything about. Sometimes, it’s a temporary error; sometimes it isn’t. Still, there are some things you can try on your end of things.
Refresh the Page
Refreshing the page is always worth a shot. Many times the 502 error is temporary, and a simple refresh might do the trick. Most browsers allow you to refresh the page by pressing Ctrl+R on Windows or Cmd+R on Mac, and also provide a Refresh button somewhere on the address bar.
It doesn’t fix the problem very often, but it takes just a second to try.
Check if the Site Is Down for Other People
Whenever you fail to reach a site (for whatever reason), you can also check if it’s just you that’s having a problem connecting, or if other people are having the same trouble. There are lots of tools out there for this, but our favorites are isitdownrightnow.com and downforeveryoneorjustme.com. Both work pretty much the same. Type in the URL you want to check, and you’ll get a result like this.
If you get a report saying the site is down for everyone, there’s not much you can do but try again later. If the report shows that the site is up, then the problem might be on your end. It’s very rare this is the case with a 502 error, but it is possible, and you can try some of the things we describe in the next few sections.
Try Another Browser
It’s possible that an issue with your browser might be causing the 502 Bad Gateway error. One easy way to check this out is to use a different browser and see if it works. You can use Google Chrome, Mozilla Firefox, Apple Safari, or Microsoft Edge. If you can see the error in the new browser as well, then you know it’s not a browser issue, and you should try another solution.
Clear Your Browser’s Cache and Cookies
If trying a different browser works, it’s possible that your main browser has cached outdated or corrupt files that might be causing the 502 error. Removing these cached files and trying to open the website could solve the problem.
It’s certainly worth trying, and we’ve got a handy guide for you on how to clear your history in any browser.
Check Your Plugins and extensions
If you use extensions on your browser, then it’s possible that one or more of the extensions are causing the problem. Try disabling all your extensions and then accessing the website. If the error disappears after that, then it’s likely that a plugin is causing the issue. Enable your plugins one by one to find the culprit.
Restart Your Devices
So, you’ve used a site checking tool and determined that the site is just down for you. And, you’ve tested another browser and are having the same problem. So you know the problem is likely something on your end, but it’s not your browser.
It is possible that there are some strange, temporary issues with your computer or your networking equipment (Wi-Fi, router, modem, etc.). A simple restart of your computer and your networking devices might help fix the problem.
Change your DNS Servers
Sometimes, DNS problems can cause 502 errors. Changing your DNS servers is not a likely fix, but it is a possible one. And it’s not too hard to do. Unless you’ve changed them yourself, your DNS servers are probably be set by your ISP. You can change them to a third-party DNS server like OpenDNS or Google DNS, and that might solve the problem.
And there are other reasons you might want to change DNS servers, too—like better speed and reliability.
Troubleshoot Elastic Load Balancer HTTP 502 Bad Gateway Errors
This article recorded how we fixed the HTTP 502 bad gateway errors with our web application.
The problem
We recently encountered an issue with our web application. The issue was first reported by our customers that our web application was getting slower and slower, and eventually down and not usable. Sometimes they could login but all the pages just stopped working properly and often hung there.
As we added a lot of new users to our application recently, our first reaction was that the system must have a bottleneck somewhere.
Our web application is a typical web application hosted on AWS. We use EC2 cluster to host the containerized web server and api server. Then the EC2 clusters are behind the two Application Load balancers, one for the web server www.example.com, and one for the API server api.example.com. Users login to www.example.com and access the web application.. Each web page will call the restful apis from api.example.com to retrieve and update data. We also have mobile apps access the apis of api.example.com directly. Behind the api.example.com is the mongodb database.
Fortunately we were able to duplicate the issue. We used chrome to login to www.example.com. Then we use the F12 developer tools to monitor the network traffic and check any exceptions from the console. We saw that the api calls failed randomly.
We first saw some exceptions from the console.
We were confused at first glance. How come we have CORS issues? We configured everything properly on the API server. If we really have a CORS issue, it should fail on every API call. Not just randomly failed on 1 of 50 calls.
After we understand how CORS works:
We realized that it was not a CORS issue. It just happened that when the OPTIONS/preflight call failed, chrome thought that the failure was caused by the CORS policy. But for our case, the random failure of the API call, when it happened to OPTIONS/preflight call, chrome complained about the CORS policy, when it happened to another call like GET, chrome will just display the http 502 bad gateway error.
It was even more confusing when chrome’s DevTools network tab by default does not capture/display the OPTIONS/preflight call. We had to go to the following url:
and disable the [Out of blink CORS] then restart chrome. Now we could see those OPTIONS/preflight api calls failed with HTTP 502 bad gateway error.
We were also able to duplicate this issue and saw some GET API calls failed randomly.
We found an easy way to duplicate this issue. We just kept clicking the different rows of a list data that would cause the browser to keep sending the preflight call and the GET call of the API server. When I clicked quickly enough like 3 clicks per seconds, after 10–20 seconds, chrome would display a HTTP 502 bad gateway error either on the preflight call or the actual GET call.
After we excluded the possibilities of CORS issues, we started to think about the backend.
We tried one thing first which is scaling up the mongodb atlas service. We thought mightbe because we got more users recently, the mongodb might not be able to handle the traffic and became the bottleneck of the system. After we scaled up the mongodb, we found out it didn’t help.
Then we went to the load balancer.
Application Load Balancer Logs
The Application Load Balancer logs every request. The Access Logs for the Application Load Balancer are saved in the S3. We can use the AWS Athena to easily query the logs and find the useful information.
We found the requests that come from my browser by using my client ip address and the time range with where clause.
What information could we find with those two lines of logs?
After reading carefully of the explanation of each field of the log in the document, the following fields are very helpful for the troubleshooting:
response_processing_time: The total time elapsed (in seconds, with millisecond precision) from the time the load balancer received the response header from the target until it started to send the response to the client. This includes both the queuing time at the load balancer and the connection acquisition time from the load balancer to the client.
elb_status_code: The status code of the response from the load balancer.
In our case, we have following values:
We had the following conclusions:
The question now became:
Why did the load balancer fail to send the request to the api server?
We searched the similar issues and found some users complained about the similar issues and fixed them by delete the load balancer and re-create the load balancer.
We tried that, but it didn’t help.
Then we went to check the api server’s logs.
Application Server Logs
Fortunately, our George and the Unbreakable Code server had a very detailed logging, and the logs were sent to the CloudWatch Logs.
We can easily query the cloudwatch logs with the CloudWatch Logs Insights.
I tried to find the logs from my browser by limiting the timestamp range.
Notice that the timestamp only accepts the epoch time. So I have to convert the time to epoch time.
But this production site had thousands of requests every minute. How could I filter the logs so that it only shows the requests coming from my browser?
Chrome DevTools allows us to set the custom user agent.
After I set the custom user agent with appending my name, I duplicated the issue again, and then I can use the following query to limit the result only from my browser.
It worked. But, I could not find the failed 502 request in the logs. I could find the request right before the failed request and the request right after the failed request.
The ELB logs complained the api server did not respond and API server logs said it didn’t receive the request. The request got lost between the load balancer and the API server. Who should take the responsibility?
The cause
We sat back and thought this again. It was obvious that issue happened before the load balancer was able to send the request data to the API server. What would the load balancer do before sending the request?
It failed to establish the TCP connection. Why did the load balancer fail to establish the TCP connection? Because the API server didn’t accept the connection. Why would the API server not accept the connection?
Thinking about the way I duplicated the issue by sending the request quick enough, I immediately thought of one possible reason: the TCP backlog.
Our api server used an open source rest api framework library. We went ahead to modify the api server by passing the backlog parameter explicitly and testing again.
Conclusion
Not every 502 bad gateway error is caused by TCP backlog setting. But with the above mythology, I think we can locate the cause of the issue and find the root cause. And the key is the logging information from every component of the system that made the issue traceable.
Ошибка 502 Bad Gateway. Как ее исправить? Что делать?
Ошибка «502 Bad Gateway» означает что запрос, который был отправлен на какой-либо Web-ресурс, не смог дойти до адресата.
Если вы являетесь владельцем сайта, а при входе на него возникает ошибка «502 Bad Gateway» то скорее всего проблема в том, что не хватает ресурсов, необходимых для обработки данных.
Распространённые проблемы:
1) Сервер не справляется с большим числом посетителей сайта (попросту не хватает вычислительной мощности).
2) Некорректная конфигурация сервера.
3) Проблемы с виртуальным хостингом, когда имеются проблемы на стороне компании-хостера.
4) Возможно имела место DDoS-атака, когда злоумышленники намеренно отправляют огромное число запросов чтобы вывести работу вашего сайта из строя.
5) Ошибка в программных скриптах.
Для исправления данной ошибки нужно оптимизировать использование сетевых ресурсов. Также если неправильно настроена конфигурация сервера или имеются проблемы на стороне хостера, то можно обратиться в службу поддержки организации, на серверах которой размещён ваш сайт.
Error: Request failed with status code 502. «Bad Gateway». #3948
Comments
isagastiberri commented Nov 25, 2021
My actions before raising this issue
I had CVAT running on a machine that unexpectedly shut down. Now, when I do the docker-compose up and I try to access it I get this errors
We are not sure what is happening, maybe the app lost connection to the database but we don’t understand why. Except for the up and down we have not changed anything from the docker-compose that was working earlier today.
I hope you can help us. Thanks a lot in advance
The text was updated successfully, but these errors were encountered:
leeyh20 commented Nov 26, 2021
Hello, I am also facing the same issue. We have not changed any settings,in fact traefik reports that everything is fine. We checked the logs and there’s nothing unusual with the logs. But no matter what settings we change, cvat still reports this error today.
It only started happening today.
azhavoro commented Nov 26, 2021
@isagastiberri Hi, please provide output of docker ps command and log file from cvat container docker logs cvat > cvat.log
isagastiberri commented Nov 26, 2021
@azhavoro The output from docker ps:
Also, find attached the logs from cvat
cvat_server.log
Looking a bit at them I noticed that the last logs are from before it broke, I’m not sure why but there are no logs showing for after the shut down
azhavoro commented Nov 26, 2021
isagastiberri commented Nov 26, 2021
Sorry, I realized I wasn’t looking at the correct logs, here you can find attached the newest ones, I just did a docker.compose down and up again.
I do have enough space in the disk now, we solved that mistake. I’ve also done docker compose down and up several times before, as whenever we had this same error that was the way to solve it, but it’s not working this time.
azhavoro commented Nov 26, 2021
Seems something wrong with your database, please attach logs from postgres container as well: cvat logs cvat_db > cvat_db.log
Thanks.
nrudakov commented Dec 1, 2021
@azhavoro I’m facing similar issue, here is my logs from cvat_db
azhavoro commented Dec 8, 2021
@azhavoro I’m facing similar issue, here is my logs from cvat_db
Your database is ok, please attach cvat container logs as well
northanapon commented Dec 22, 2021 •
I have the same 502 Bad Gateway issue when I tried to upgrade CVAT today. I tried removing the old images and volumes before reinstalling them, but still 502. The Traefik dashboard works though.
This is my docker ps :
Here are the log files:
northanapon commented Dec 23, 2021
My issue was resolved.
DP1701 commented Jan 31, 2022
Hello all, i also get this error message, but I can still log in and use CVAT.
To install CVAT, I followed the installation instructions for macOS Mojave (link). The difference is that I modified the docker-compose.yml file (starting at line 110) and added the docker-compose.override.yml file. The goal is to store the CVAT data on an external disk and to have a share path for uploading. I have attached both files. Unfortunately I don’t know why the error appears before the login.
I currently have version 1.7.0 installed.
sinnud commented Feb 13, 2022
I met the same error for develop branch. Then I changed to CVAT with tag v2.0.0-alpha and the error disappeared. Looks the develop branch have extra code to raise this issue.
yustiks commented Feb 28, 2022
I couldn’t find ‘v2.0.0-alpha’, I assume it is ‘release-2.0.0’?
sinnud commented Feb 28, 2022
@yustiks Looks v2.0.0-alpha is gone because release-2.0.0 is ready. Wish this bug is gone.
yustiks commented Feb 28, 2022
@yustiks Looks v2.0.0-alpha is gone because release-2.0.0 is ready. Wish this bug is gone.
I still have this issue with release-2.0.0
nmanovic commented Feb 28, 2022
yustiks commented Mar 1, 2022
yustiks commented Mar 1, 2022
and ‘docker ps’
nmanovic commented Mar 1, 2022
bsekachev commented Mar 1, 2022
There was recent issue with similar exception #4388
The instance was incorrectly configured there.
Need to work with client-side logs and requests details, to say more.
Ошибка 502: Bad Gateway — как исправить?
Мы привыкли бродить по просторам Интернета. Открывая то одну страничку, то другую, мы узнаем новости, смотрим погоду на ближайшие дни, приглядываемся к товарам, или просто играем в браузерные игры.
И вот иногда случается так, что при попытке открыть любимый сайт, вместо ожидаемой и привычной картинки, вываливается ошибка 502.
Описание 502 ошибки
Ошибка 502: Bad Gateway имеет массу причин, но все они сводятся к одному — Ваш браузер получил не допустимый ответ от сервера, на котором находится сайт, либо DNS сервера, к которому обратился ваш браузер.
В любом случае, при получении такого недопустимого ответа, Вас — как пользователя, нужно проинформировать о неполадке, что браузер и делает выводя страницу с 502 ошибкой сервера.
Как исправить ошибку
Для начала, необходимо убедится, что с вашим интернет-соединением все в порядке. Для этого откройте в браузере новую вкладку и наберите адрес сайта, который с вероятностью 99,9% доступен — это может быть http://google.ru или http://yandex.ru. Эти две поисковые машины доступны практически всегда.
Реклама
С другой стороны, раз уж вы попали с компьютера на котором отобразилась 502-я ошибка — сюда, то с вашим интернет-соединением точно все в порядке.
Теперь нужно попробовать очистить cookies интересующего сайта в браузере.
В Google Chrome, Chromium, это делается так:
Жмем «Меню» => идем в «Дополнительные инструменты» => «Удаление данных о просмотренных страницах…»
Далее делаем все как на рисунке. У меня стоит опция удалить за последний час. В случае неудачи, можно будет попробовать очистку за больший диапазон времени.
Как это проделать в остальных браузерах, вы можете сами разобраться без труда, уделив несколько минут их изучению.
Отзывы и обзоры хостинга
Ошибка 502 Bad Gateway nginx. Как исправить
Эта статья поможет разобраться, почему на сайтах время от времени появляется ошибка 502 Bad Gateway nginx (HTTP Error 502) и как эту проблему решить.
Если вы посетитель
Если вы не можете попасть на сайт из-за ошибки 502, сделать можно не так много:
Если вы администратор сайта
Если эта ошибка возникает, значит HTTP-запросы от посетителей к вашему сайту идут через так называемый «шлюз», программу-посредник. Например, если на хостинге перед веб-сервером Apache стоит веб-сервер nginx, то nginx будет шлюзом.
502-ая ошибка означает, что запрос от клиента прошел nginx, попал к Apache, и Apache не смог запрос обработать, о чем сообщил nginx’у. В результате nginx отдает клиенту ошибку.
Если PHP работает в режиме FastCGI, то любой веб-сервер перед ним будет шлюзом.
Почему Apache не смог обработать запрос? Как это исправить?
Скорее всего, если сайт раньше работал, а теперь не открывается, дело не в ошибках конфигурации среды. Причина может быть в нехватке ресурсов сервера, и, следовательно, в невозможности обслужить всех клиентов. В частности, проблема может быть в нехватке оперативной памяти. Или вы можете упираться в какое-то ограничение, например, на количество процессов. Иногда Apache или ваше приложение могут периодически падать/перезапускаться, в эти моменты фронт-серверу тоже ничего не остаётся, кроме как отдавать ошибку 502. Такое может случиться и на VPS, и на shared-хостинге.
Возможен случай, когда ошибка 502 постоянная, возникла на этапе настройки сервера. Его сейчас подробно рассматривать не будем. Скорее всего, фронт-сервер и то, что находится за ним, не состыкованы. Или вообще Apache не запущен.
Если у вас VPS
Если PHP работает через FastCGI, то на сервере может не хватать php-cgi процессов в моменты, когда на сайте много посетителей, пришел прожорливый бот, кто-то скачивает ваш сайт целиком или идёт DoS-атака. Веб-серверу нужно бы запустить дополнительные процессы, но памяти под них уже нет. Значит, нужно добавить памяти либо оптимизировать расход доступной
Если дело в нехватке памяти, то в логах будут ошибки OOM (out of memory). Когда ОС очень нужна память, то ядро может попытаться освободить её при помощи механизма OOM killer, просто убивая активные процессы. Например, здесь пришлось пожертвовать Апачем:
Out of memory: kill process 1718 (apache2) score 56789 or a child
Killed process 22504 (apache2)
[core:notice] [pid 5795] AH00052: child pid 5858 exit signal Segmentation fault (11)
[mpm_prefork:notice] [pid 5795] AH00169: caught SIGTERM, shutting down
Если это происходит со строгой периодичностью, то нужно поискать связь с другими процессами с похожим расписанием. Например, со службой мониторинга или задачами в кроне.
Устранение ошибок «Недопустимый шлюз» в шлюзе приложений
Практическое руководство по устранению ошибок «Недопустимый шлюз» (502), полученных при использовании шлюза приложений Azure.
В этой статье предусмотрено использование модуля Azure Az PowerShell, который является рекомендуемым модулем PowerShell для взаимодействия с Azure. Чтобы начать работу с модулем Az PowerShell, ознакомьтесь со статьей Установка Azure PowerShell. Дополнительные сведения см. в статье Перенос Azure PowerShell с AzureRM на Az.
Обзор
Проблема группы безопасности сети, определенного пользователем маршрута или пользовательской службы DNS
Причина
Если доступ к серверной части заблокирован из-за группы безопасности сети, определяемого пользователем маршрута или пользовательской службы DNS, экземпляры шлюза приложений не могут подключиться к внутреннему пулу. Это вызывает сбои пробы и приводит к ошибкам 502.
Группа безопасности сети или определяемый пользователем маршрут могут присутствовать в подсети шлюза приложений либо в подсети с развернутыми виртуальными машинами приложений.
Аналогичным образом наличие пользовательской службы DNS в виртуальной сети также может вызвать проблемы. Полное доменное имя, используемое для членов внутреннего пула, может неправильно разрешаться DNS-сервером, настроенным пользователем для виртуальной сети.
Решение
Проверьте конфигурацию NSG, UDR и DNS, сделав следующее:
При ее наличии убедитесь, что DNS-сервер может правильно разрешить полное доменное имя участника внутреннего пула.
Проблемы со стандартной пробой работоспособности
Причина
Ошибки 502 часто указывают, что стандартная проба работоспособности не может связаться с виртуальными машинами серверной части.
При предоставлении экземпляра шлюза приложений для каждого серверного пула адресов автоматически настраивается стандартная проба работоспособности с помощью параметра BackendHttpSetting. Пользователю ничего не нужно вводить для настройки этой пробы. В частности, при настройке правила балансировки нагрузки создается связь между параметром BackendHttpSetting и серверным пулом адресов. Стандартная проба настраивается для каждой из связей. Шлюз приложений периодически проверяет работоспособность каждого экземпляра в серверном пуле адресов. Для этого он подключается к нужным экземплярам, пользуясь портом, заданным в параметре BackendHttpSetting.
В таблице приведены значения, связанные со стандартной пробой работоспособности:
Свойства проверки | Значение | Описание |
---|---|---|
URL-адрес проверки | http://127.0.0.1/ | URL-адрес |
Интервал | 30 | Интервал проверки в секундах |
Время ожидания | 30 | Время ожидания проверки в секундах |
Пороговое значение сбоя | 3 | Количество повторных попыток проверки. Сервер внутреннего пула считается неисправным, когда количество повторных неудачных попыток проверки достигает порогового значения сбоя. |
Решение
Проблемы с пользовательскими пробами работоспособности
Причина
Пользовательские пробы работоспособности более гибкие по сравнению со стандартными. Для пользовательских проб можно настроить интервал, URL-адрес и путь к ним (для тестирования), а также число неудачных откликов, после которых экземпляр внутреннего пула будет считаться неработоспособным.
Добавлены следующие дополнительные свойства.
Решение
Настройте пользовательскую пробу производительности правильно, как описано в таблице выше. Кроме действий по устранению неполадок, описанных выше, требуется соблюдение следующих условий:
Время ожидания запроса
Причина
При получении запроса пользователя шлюз приложений применяет настроенные правила к запросу и направляет его экземпляру серверного пула. Затем в течение указанного интервала он ожидает отклик от серверного экземпляра. По умолчанию этот интервал составляет 20 секунд. В Шлюзе приложений версии 1, если в течение этого времени шлюз приложений не получает отклик от серверного приложения, для пользовательского запроса отображается ошибка 502. Если в течение этого времени Шлюз приложений версии 2 не получает отклик от серверного приложения, в нем будет произведена попытка передать запрос во второй элемент пула серверной части. Если второй запрос завершится неудачей, запрос пользователя получит ошибку 502.
Решение
Шлюз приложений позволяет настроить этот параметр с помощью параметра BackendHttpSetting, который впоследствии можно применить к разным пулам. Для разных серверных пулов могут быть установлены разные настройки BackendHttpSetting, а значит и разное время ожидания запроса.
Пустой серверный пул адресов
Причина
Если для шлюза приложений в серверном пуле адресов не настроены виртуальные машины или масштабируемый набор виртуальных машин, шлюз не сможет отправлять запросы пользователей, выдавая ошибку недопустимого шлюза.
Решение
Убедитесь, что серверный пул адресов не пуст. Это можно сделать с помощью PowerShell, интерфейса командной строки или на портале.
Выходные данные командлета, приведенного выше, должны содержать непустой серверный пул адресов. В примере ниже возвращаются два пула, в которых для серверных виртуальных машин указано полное доменное имя или IP-адрес. Состояние подготовки серверного пула адресов должно быть «Выполнено».
Неработоспособные экземпляры в серверном пуле адресов
Причина
Если неработоспособными являются все экземпляры серверного пула адресов, шлюзу приложений некуда отправлять запросы пользователей. То же самое происходит, когда серверные экземпляры работоспособны, но в них не развернуто требуемое приложение.
Решение
Сделайте экземпляры работоспособными и правильно настройте приложение. Проверьте, могут ли серверные экземпляры отвечать на запрос при проверке связи от другой виртуальной машины в виртуальной сети. Если настроена общедоступная конечная точка, убедитесь, что запрос браузера к веб-приложению подлежит обслуживанию.
Дальнейшие действия
Если описанные выше шаги не устранят проблему, отправьте запрос в службу поддержки.
Webhook 502 error – Fixed
by S K Asif Akram | Oct 29, 2019
Webhook comes handy while connecting different applications.
However, it often shows up Webhook 502 error when there is a problem in getting a webserver response.
Such errors can be tricky and web developers may even think of giving up.
At Bobcares, we get requests to solve 502 errors as part of our Server Management Services.
Today, let’s analyze the cause for Webhook errors and see how our Support Team fix it for our customers.
What is a webhook?
Firstly, let’s learn more about webhook as such.
Webhooks are calls from one server to another. To clarify, on some specific events, it will trigger a call.
For example, say we have two domains abc.com and xyz.com. Meanwhile, if you signup on abc.com, it will send a request to xyz.com. Site xyz.com may use the call to send an email or something like that.
For instance, payment solutions like Stripe have a webhook that will automatically send an email to a customer whenever a payment fails to go through.
Cause and Fix for webhook 502 error
Now let’s check on the causes and fixes for 502 errors while using Webhooks.
There are multiple reasons for 502 error while using webhook. But it is a bit tricky to debug as it may or may not have proper logs. Depending on the webhook application you are using, the logs will almost look like the below image.
Let’s check the reasons in detail.
1. Network Error
Our team initially starts checking whether the domain is resolving or not. In other words, if we see an error like “failed to resolve” then we check the DNS.
In many cases, due to recent changes in DNS, the domain may not resolve to the proper IP address. As a result, this kind of error will appear.
Solution: As a temporary workaround, we suggest our clients to replace the domain name with the IP address in the webhook application. Additionally, we also suggest fixes to make the domain resolve to the correct IP.
2. File permission
The error itself says it’s a server-side issue. So we can directly look into the server instead of going through client-side codes. In such cases, we ask for more info from the client. If it stopped working after recent changes then probably the file permission will be the culprit.
Solution: We look for recently changed files and fix permissions or we restore from backups.
3. Firewall settings cause Webhook 502 error
The server Firewall directly affects the connection to and from the server. By default, firewall configuration allows only trusted IP address. And, it may block the request from unknown IP addresses. It can be the server or even the router firewall.
Solution: Here, our Dedicated Engineers debug and fix the firewall rules that block the request. This solves the connection error between the applications.
4. Server connectivity issue – webhook 502 error
It is entirely possible that the server may not be responding. As a result, the webhook returns 502 error.
A server can crash because of exhausting memory or a DDOS attack. Therefore it will return the webhook 502 error.
Solution: Our team mitigates the DDOS attack by taking necessary precautions such as installing mod_evasive. This essentially fixes the server and bring the application back online.
5. Faulty programming
Sometimes destination server receives the request but fails to respond due to faulty code. Hence, webhook respond with a 502 error.
Solution: We usually fix simple codes or give a recommendation to the app developers regarding the probable error causes. This helps the web developers to fix the code errors.
[Need assistance to fix webhook errors? We’ll help you.]
Conclusion
In short, the webhook 502 error happens when there is a failure in getting a response from the server. Today, we saw how our Support Engineers fix errors related to webhook.
Related posts:
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
How To Fix A 502 Bad Gateway Cloudflare Error (Fast)
Sometimes, Cloudflare can also trigger the 502 Bad Gateway error if it cannot reach the origin server or if its services are down. The error looks like this 👇🏻
Though it’s a temporary error, it can appear quite frequently depending on your hosting provider and website setup.
So why does this error occur, and how can you fix a 502 Bad Gateway Cloudflare error?
What Does 502 Bad Gateway Cloudflare Error Mean?
A 502 Bad Gateway Error occurs when Cloudflare cannot establish a valid connection with your website’s origin web server. While this error message relates to the server-side (i.e. your web host), it can also happen if Cloudflare service is down or not correctly configured.
Was that a horrible explanation? Sorry, let me try again.
(Or click here if you’re just looking for how to fix this 502 Bad Gateway Cloudflare error)
Every time you visit a website, the browser sends a request to the origin server. The server then processes the request and sends it back to the browser with an HTTP status code.
But when you’re using Cloudflare on your website, the request is sent to Cloudflare before it reaches the client.
And a 502 Bad Gateway error occurs when Cloudflare cannot establish a valid connection with your website’s origin web server.
While this error message relates to the server-side, it can also happen if Cloudflare service is down or not configured correctly.
Different Variations of a 502 Bad Gateway Error
Based on your web server and browser, you might see a different 502 error, but they all mean the same thing:
Some websites can also customize how a bad 502 gateway error looks.
However, all variations have the same meaning that the server acting as a proxy has not received a valid response from the origin server.
Causes for a Cloudflare 502 Bad Gateway Error
The two possible causes for this error are:
Error code from the origin server is most common as excessive server loads or network failures can result in server downtime.
If you have a WordPress website, then too many MySQL connections or low PHP memory limits can lead to request timeout. As a result, the website starts loading slowly and gives 502 errors.
Several other reasons can lead to a bad gateway error—incorrect DNS records, request block by a firewall, service failure (like PHP-FPM and cache services), or plugin/theme conflict in WordPress.
How to Fix a 502 Bad Gateway Cloudflare Error
When a 502 Bad Gateway error occurs, it’s mostly related to the server-side response, but Cloudflare can also cause this error. So below are a few ways you can apply to fix the problem and get your website up and running.
1. Clear Your Cache And Reload The Page
Little is more frustrating than your IT guy telling you to reset your modem or turn your computer off and on again.
But they do it for a reason: it’s the most common (and easiest) way to fix the issue.
Cloudflare-related 502 Bad Gateway errors often occur due to temporary connection problems.
So simply waiting 5 minutes and reloading the page can do the trick.
If you still see a 502 bad gateway error, then clear your browser cache and reload the page again.
To clear the browser cache, you can hold down Ctrl + F5 for Windows and Linux browsers, and Cmd + Shift + R for Chrome and Safari on Mac.
This shortcut (known as a “hard refresh”) will bypass the cache for the specific page that you’re on, and the site will come back if it’s just a temporary connection issue.
2. Check Your DNS Servers
Sometimes, DNS can also cause 502 bad gateway errors.
If you’ve recently changed your web hosting service or moved to a different IP address, then it’s recommended to wait for 24 hours for the DNS changes to resolve.
You can also change your DNS to any third-party DNS servers like Google DNS to see if that solves the 502 error.
3. Check Your Web Hosting
The most common cause of Cloudflare 502 Bad Gateway error is when the web hosting server is down — especially on shared hostings where servers kill the processes that take too long to complete.
When that happens, Cloudflare returns a Cloudflare branded HTTP 502 bad gateway error.
To fix this, you can contact your hosting provider to make sure that the web server is performing correctly.
Sometimes, a sudden increase in traffic can also cause the web server to crash. When that happens, the server becomes temporarily overloaded, resulting in loss of a connection between the server and Cloudflare.
Servers can get overloaded due to excessive CPU and memory usage as well.
A lot of hostings also put servers into maintenance without any notification. The only way to solve the problem, in this case, is to wait for the hosting to finish the server maintenance.
So if the problem is on the host end, it’s best to contact the hosting customer support as they will help you faster.
4. Disable Cloudflare Proxy
If your hosting and DNS is fine, you can disable Cloudflare’s proxy for a while, and then visit the site again. If you’re using a dedicated CDN (content delivery network) in addition to Cloudflare, you can disable that too.
Cloudflare and CDNs can also experience system outages, that rarely happens, but a possible situation.
If the 502 error goes away after you disable Cloudflare proxy, then you will have to contact the Cloudflare support to find out the cause of the issue.
Also, if you see the following screen, then the error is because of Cloudflare.
To troubleshoot this, you can keep the Cloudflare proxy disabled, and share the following details with Cloudflare support:
Cloudflare usually replies within 1 to 3 business days to users on the free plan. You can also post your issue on the Cloudflare community platform, where other users might help you faster.
Before raising the problem in the Cloudflare support center, it’s good to check their System Status to make sure that Cloudflare services are working fine, and only you’re facing the 502 bad gateway error.
5. Plugin/Theme Conflict in WordPress
If you’re on a WordPress website, then some plugins and themes can also cause 502 errors when PHP scripts take too long for execution.
To check, go to “Plugins” in your WordPress dashboard (yourwebsite.com/wp-admin/), disable all the plugins, and see if the site works.
If this fixes the error, then activate the plugins one by one and reload the site after each activation. When you see the 502 error, you’ve found the cause of the problem.
But if you can’t access your WordPress dashboard, then you can disable the plugins via FTP by changing the name of the “Plugins” folder to something else (like “Old_Plugins”).
Once you have found the issue causing plugin/theme, you can contact their developers and notify them about the problem.
Summary
Bad Gateway errors are unexpected and can be frustrating. The best way to solve it is to see if the DNS is working fine, and your web server is running properly. You can also check the server error logs to pinpoint the issue triggered by any recently added application.
If it’s a Cloudflare issue, keep the proxy disabled and raise a ticket on their customer support.
Finally, if nothing works, reach out to your hosting provider and let them know about the error. They can identify the problem from their end and help you fix it as well.
Please DM me if you have any questions about this Cloudflare article (or have some feedback to make it better 😄️).
About Jake Sacino
After working as an engineer and consultant for a bunch of big companies, Jake now works as a full-time SEO & software engineer.
Here are some other articles you might find useful
Ngrok errors ‘502 bad gateway’
Quite new to using any sort of Web App stuff, and I’ve been trying to slowly build a Facebook Messenger Bot. When I try to use ngrok I can’t visit the address I’m given, i.e:
is what I’m putting in the command line, and it’s returning this:
But when I take the address ‘https://ea986ca5.ngrok.io’ as is required by the Facebook developer’s page, it says:
Is it a problem with my local port? Thanks!
21 Answers 21
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
This worked for me
Im using visual studio 2017 dont know if it effects anthing.
Try to explicitly set the localhost IP:
ngrok http 127.0.0.1:5000 instead of ngrok http 5000
Just as @njzk2 should have said, if you don’t have a web server running so it cannot work. I would like to make it clearer to you, if you are still confused.
What ngrok does, is to make your local server (running on localhost) to be available to the outside world (rest of the internet). On its own, it is not a web server. So for your bot development you need to have a web server running on a defined port (which in your case is 5000). Then you can point ngrok to this port so that it will redirect requests sent to your public address to the program running on that port. The web server will then accept and handle requests from Facebook
Исправляем внутреннюю ошибку сервера «HTTP Internal Server 500 ERROR» и получаем доступ к любимому сайту
Ошибка: «500 Internal Server Error» – популярная проблема, с которой сталкивался практически каждый проектировщик сайтов. Основная причина возникновения проблемы – некорректная работа сервера. Но может ли «http 500 ошибка» появиться из-за проблем с браузером? По каким именно причинам она возникает? И как с ней бороться? – Ниже мы узнаем ответы на эти вопросы.
Описание неполадки и причины возникновения
Ошибка: «500 Internal Server Error» – это внутренняя неполадка, которая возникает из-за некорректной работы удаленного сервера. Механизм этой проблемы следующий:
Основные причины возникновения неполадки:
Чаще всего ошибка 500 отображается в виде надписи: «Internal Server Error» на белом фоне. Однако иногда текст надписи может быть другим:
Способы исправления
Рассмотрим основные способы устранения ошибки – «http 500 Internal Server» в зависимости от причин ее возникновения.
Проверяем доступ в интернет, перезапускаем браузер
В редких случаях временная ошибка (500) возникает из-за серьезных проблем с браузером или некорректного подключения к интернету. Решение:
Обновляем CMS-модуль
В редких случаях проблема возникает из-за того, что вы пользуетесь старой версией CMS-модуля. Решение неисправности будет тривиальным – вам нужно просто обновить свой модуль. Метод обновления CMS-модуля напрямую зависит от его типа, однако обычно для обновления нужно просто открыть консоль администрирования и найти блок работы с обновлениями.
Например, в случае «Wordpress» – вы проходите авторизацию и открываете вкладку «Updates» – если есть неустановленные обновления, то сверху должна появиться строка «Please Update Now».
Проверяем права доступа
Достаточно часто неполадка возникает из-за некорректных прав доступа. Например, если разрешить всем пользователям вносить исправления в скрипт-обработчик, то сервер автоматически заблокирует такой сайт. Поэтому нужно обязательно проверить права доступа к каждому файлу – например, с помощью файлового менеджера «FileZilla»:
Проверяем файл «.htaccess»
Ошибка «http 500» на сайте может возникнуть из-за некорректной конфигурации файла «htaccess», который находится в корневом каталоге вашего сайта. Исправить этот файл можно двумя способами:
Анализируем скрипт-обработчик
Скрипт может обрабатывать внешние запросы в течение ограниченного времени – в противном случае он прекращает работу и возвращает ошибку «http 500». Но есть решение:
Тестируем плагины
Внутренняя ошибка «http сервера – 500» может возникнуть из-за некорректной работы плагинов, а также из-за несовместимости плагинов между собой. К сожалению, универсального рецепта решения проблемы в данном случае нет. Для устранения неисправности нужно вручную по одному отключать плагины и проверять работоспособность сайта.
После установления источника проблемы нужно либо изменить формат работы плагина, либо отключить его полностью. Можно попробовать его обновить или переустановить вручную, заранее перед этим скачав его с официального сайта.
Expo commands returning 502/504s #2300
Comments
1337LutZ commented Jun 23, 2020 •
I’ve talked to @quinlanj on the Expo Slack and she asked me to create a bug report here with my use cases.
Description
When creating an Expo build using the expo-cli it will quite often result an 504 Gateway Timeout error when running any expo related cli task.
These errors got much worse lately and are costing our developers quite some valuable development/testing time due to having manually retrigger builds that fail.
Expected Behavior
When I run expo «login» «—non-interactive» «-u» «$EXPO_USERNAME» «-p» «$EXPO_PASSWORD» I expect to successfully login
Observed Behavior
expo «login» «—non-interactive» «-u» «$EXPO_USERNAME» «-p» «$EXPO_PASSWORD»
Environment
Output expo diagnostics
Bitrise CICD
Stack: Xcode 11.6.x, on macOS 10.15.4
Elite machine: 4xCPU (Intel Xeon E5-1650 v2) / 8 GB RAM
Reproducible Demo
I dont have a demo, but extensive logs and description of the used commands.
The text was updated successfully, but these errors were encountered:
Как исправить ошибку 502 Bad Gateway в WordPress
Любая ошибка, из-за которой ваш сайт WordPress становится непригодным для использования, является серьезным поводом для беспокойства, потому что это означает потерю дохода, низкий рейтинг SEO и чрезмерный стресс для вас. Одна из самых печально известных ошибок, когда-либо появлявшихся в Интернете, – это ошибка 502 неверного шлюза. Это неприятная и неприятная проблема, потому что она может возникнуть по ряду причин, которые затрудняют поиск и устранение неисправностей.
Но не волнуйтесь, мы вас поддержим. Если вы хотите исправить ошибку 502 неверного шлюза на своем сайте WordPress, сделайте передышку, потому что мы предлагаем вам пару проверенных решений. К концу сегодняшнего поста вы должны раз и навсегда избавиться от ошибки 502 bad gateway.
Если это похоже на сделку, от которой вы даже не мечтали отказаться, возьмите себе чашку кофе и поехали.
Что такое ошибка 502 Bad Gateway?
Перво-наперво, что во имя вопроса является ошибкой 502 неверного шлюза? Вот небольшой урок о хостинге. Хостинг вашего сайта WordPress обычно включает несколько серверов.
Самая простая настройка может включать от четырех до пяти (иш) серверов, а именно:
Теперь, когда вы вводите URL-адрес своего сайта в браузер и нажимаете ENTER, браузер отправляет пару HTTP-запросов на обратный прокси-сервер.
Затем резервный прокси-сервер направляет запросы на соответствующие серверы. Например, запросы данных, хранящихся в вашей базе данных, направляются на сервер базы данных. Запросы статических файлов направляются на веб-сервер, а запросы, требующие PHP, обрабатываются сервером приложений.
Затем каждый сервер отправляет данные обратно на обратный прокси-сервер, который затем отправляет данные в ваш браузер, и ваш сайт загружается. Просто как A, B, C – пусть вас не смущают такие жесткие слова, как обратный прокси.
Если один из серверов отправляет неверный ответ обратному прокси-серверу, ваш веб-сайт не загружается в вашем браузере должным образом. Вместо этого обратный прокси-сервер показывает ошибку 502 неверного шлюза.
Животное самых разных форм
Ошибка 502 неверного шлюза может принимать различные формы, например:
Что вызывает ошибку 502 Bad Gateway?
Хотя ошибка 502 неверный шлюз обычно возникает на стороне сервера, она также может возникать из-за проблем на вашей стороне. Вот несколько причин, по которым вы сталкиваетесь с ошибкой 502 неверного шлюза в произвольном порядке:
Как вы можете видеть из нашего краткого списка выше, ошибка 502 неверного шлюза может быть вызвана несколькими причинами. Это означает, что вам нужно попробовать разные решения, чтобы исправить ошибку.
При этом давайте устраним ошибку 502 неверного шлюза на вашем сайте WordPress.
Как исправить ошибку 502 Bad Gateway в WordPress
Хотя обычному Джо эта ошибка может показаться проблематичной, на самом деле ее невероятно легко исправить. Вам просто нужно немного терпения, чтобы попробовать следующие решения.
1 Обновите / перезагрузите свой сайт
Как мы уже упоминали, в большинстве случаев печально известная ошибка 502 неверного шлюза происходит на стороне сервера, особенно если вы используете общий хостинг. Резкий всплеск трафика может истощить ресурсы вашего сервера, оставив вас в плену этой неприятной ошибки. В других случаях ваши серверы могут работать неправильно или отключаться по ряду причин.
Хостинг-провайдеры обычно решают проблему немедленно, потому что владельцы веб-сайтов страстно ненавидят простои. Кроме того, они теряют доход, когда сайты не работают.
Поэтому, прежде чем выдергивать волосы и страдать от панических атак, попробуйте пару раз обновить свой сайт WordPress, чтобы увидеть, исчезнет ли ошибка сама по себе. Кроме того, попробуйте другой браузер или другое устройство, чтобы узнать, разрешится ли ошибка сама собой. Тем не менее, чтобы убедиться, что проблема не на стороне сервера, протестируйте свой сайт с помощью такого инструмента, как isup.me.
Однако, если ошибка не исчезнет после попытки исправить это, перейдите к следующему решению в этом сообщении.
2 Очистите кеш браузера.
Вы не можете исправить ошибку 502 неверного шлюза даже после обновления браузера? Если это так, выполните аппаратное обновление в своем браузере (CTRL + F5 в системах Windows и CMD + CTRL + R в системах OS X). Избавляется ли выполнение аппаратного обновления от неприятной ошибки, связанной с ошибкой 502 неверного шлюза? Нет?
Что ж, вы можете попробовать очистить кеш браузера напрямую, используя советы, которые мы приводим в том, как очистить кеш WordPress. Устранена ли неприятная ошибка после очистки кеша? Если так, прекратите читать и танцуйте весело. Даже сальто назад. Шутки в сторону.
Если ошибка по-прежнему не устранена, может помочь следующее решение.
3 Временно отключите CDN
Используете ли вы сеть доставки контента, такую как CloudFlare, KeyCDN или другой CDN для WordPress? Сети CDN обычно направляют трафик вашего сайта на свои серверы, чтобы предложить вам лучшую производительность и безопасность сайта.
Проблема на их серверах может оставить вас с проблемой 502 плохого шлюза. Кроме того, вы можете столкнуться с ошибкой 502 неверного шлюза, если вы неправильно настроите свой CDN.
Чтобы узнать, является ли ваш CDN причиной ваших 502 проблем, приостановите CDN и обновите свой сайт. Это заставляет ваш сайт загружаться напрямую с ваших хост-серверов.
Ошибка исчезла после приостановки CDN? Если да, оставьте обслуживание приостановленным и обратитесь в их отдел поддержки. Обычно они решают проблему быстро, а это значит, что вам придется какое-то время обходиться без CDN.
У каждой CDN свой интерфейс, а это значит, что вам нужно уточнить у своего CDN, как приостановить обслуживание. Однако, исходя из моего опыта, приостановить CDN проще простого, поэтому я не ожидаю, что у вас возникнут какие-либо проблемы.
4 Проблемы с DNS
DNS (сокращение от системы доменных имен) – это то, как доменные имена (например, wpexplorer.com) совпадают с соответствующими IP-адресами. Если что-то не так с настройками DNS, вы можете ожидать ошибку 502 плохого шлюза среди других проблем.
Недавно переехали на нового хозяина? Перенос включает перенастройку ваших DNS-серверов. Распространение DNS занимает время, иногда до 48 часов и более.
Если вы столкнулись с ошибкой 502 неверного шлюза после миграции, подождите, пока изменения DNS распространятся, или, если это необходимо, обратитесь к своему хосту за дальнейшими советами и помощью.
5 Проверьте свою тему и плагины.
Кажется, пока не удается исправить ошибку? Возможно, проблема в ваших плагинах или теме. Ваша тема или один из ваших плагинов может запускать скрипт, который не работает с вашим сервером.
В результате сервер завершает работу сценария, что вызывает ошибку 502 неверный шлюз. Что делать? Давайте начнем с ваших плагинов.
6 Плагины для устранения неполадок
Вы, вероятно, не можете войти в панель администратора WordPress из-за ошибки. Как тогда вы будете устранять неполадки плагинов без доступа к админке WordPress?
Ну все просто. Войдите в свой корневой каталог WordPress (обычно это public_html, но может быть что-то еще, в зависимости от того, где вы установили свой сайт), используя FTP-приложение, такое как Filezilla или File Manager в cPanel.
Обновите свой сайт, чтобы увидеть, исчезла ли ошибка. Если вы видите свой сайт вместо ошибки, проблема в одном из ваших плагинов.
Переименуйте plugins.old обратно в плагины и войдите в панель администратора WordPress. Пора найти проблемный плагин.
Активируйте плагины один за другим, перезагружая свой сайт после каждой активации. Повторяйте это, пока не определите плагин, вызывающий проблемы. Проблемный плагин, очевидно, воссоздает ошибку 502 неверного шлюза при активации, которая может заблокировать вас из области администратора.
Полностью отключите или удалите плагин через FTP или файловый менеджер, получите альтернативу или обратитесь к разработчику за дополнительной поддержкой.
7 Устранение неполадок активной темы
Если ваши проблемы начались после обновления вашего сайта, то есть тем, плагинов и WordPress, а деактивация плагинов ничего не исправляет, вам необходимо устранить неполадки в вашей теме WordPress.
Проверка, является ли ваша тема проблемой, немного отличается от плагинов для устранения неполадок. Давай покончим с этим.
Войдите в корневой каталог WordPress через FTP или файловый менеджер. Затем перейдите к wp-content> themes и найдите свою активную тему.
Переименуйте папку активной темы во что-то вроде total.old. Это отключит активную тему и активирует тему WordPress по умолчанию.
Перезагрузите сайт, чтобы проверить, исчезла ли ошибка. Ошибка все еще существует? Это означает, что с вашей темой все в порядке, и в этом случае вам следует переименовать папку с темой обратно в ее исходное имя.
Если ошибка исчезнет, обратитесь к разработчику вашей темы за дополнительной помощью или приобретите профессиональную тему, такую как наша собственная Total.
8 Если проблема не исчезнет, обратитесь к хозяину.
По-прежнему не можете исправить ошибку 502 плохого шлюза на вашем сайте WordPress даже после попытки всех вышеперечисленных решений?
Возможно, проблема на стороне сервера, поэтому просто свяжитесь со своим хостом и получите профессиональную помощь. При этом подумайте о приобретении хоста верхнего уровня, чтобы избежать этой ошибки из-за меньшего количества ресурсов сервера, доступных в планах общего хостинга.
Заключение
Хотя это немного сбивает с толку и разочаровывает, исправить ошибку 502 плохого шлюза легко с помощью решений, которые мы описываем в этом посте. Мы надеемся, что наш пост указал вам правильное направление в этом отношении.
Есть ли у вас какие-либо мысли, вопросы или дополнительные исправления? Помогите нам расширить этот пост, поделившись своими советами, запросами и идеями в разделе комментариев ниже.
A Simple Explanation of a 502 Bad Gateway Error & How to Resolve It
What causes a 502 bad gateway error?
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.
What Is a 502 Bad Gateway Error?
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.
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.
How to Fix a 502 Bad Gateway Error
1. 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.
2. 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.
3. 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.
4. 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.
5. 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.
6. 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.
7. 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.
Originally published Jun 18, 2019 8:27:00 PM, updated October 05 2020
Troubleshoot HTTP errors of «502 bad gateway» and «503 service unavailable» in Azure App Service
«502 bad gateway» and «503 service unavailable» are common errors in your app hosted in Azure App Service. This article helps you troubleshoot these errors.
If you need more help at any point in this article, you can contact the Azure experts on the MSDN Azure and the Stack Overflow forums. Alternatively, you can also file an Azure support incident. Go to the Azure Support site and click on Get Support.
Symptom
When you browse to the app, it returns a HTTP «502 Bad Gateway» error or a HTTP «503 Service Unavailable» error.
Cause
This problem is often caused by application level issues, such as:
Troubleshooting steps to solve «502 bad gateway» and «503 service unavailable» errors
Troubleshooting can be divided into three distinct tasks, in sequential order:
App Service gives you various options at each step.
1. Observe and monitor application behavior
Track Service health
Microsoft Azure publicizes each time there is a service interruption or performance degradation. You can track the health of the service on the Azure Portal. For more information, see Track service health.
Monitor your app
This option enables you to find out if your application is having any issues. In your app’s blade, click the Requests and errors tile. The Metric blade will show you all the metrics you can add.
Some of the metrics that you might want to monitor for your app are
For more information, see:
2. Collect data
Use the diagnostics tool
App Service provides an intelligent and interactive experience to help you troubleshoot your app with no configuration required. When you do run into issues with your app, the diagnostics tool will point out what’s wrong to guide you to the right information to more easily and quickly troubleshoot and resolve the issue.
To access App Service diagnostics, navigate to your App Service app or App Service Environment in the Azure portal. In the left navigation, click on Diagnose and solve problems.
Use the Kudu Debug Console
App Service comes with a debug console that you can use for debugging, exploring, uploading files, as well as JSON endpoints for getting information about your environment. This is called the Kudu Console or the SCM Dashboard for your app.
Some of the things that Kudu provides are:
Another useful feature of Kudu is that, in case your application is throwing first-chance exceptions, you can use Kudu and the SysInternals tool Procdump to create memory dumps. These memory dumps are snapshots of the process and can often help you troubleshoot more complicated issues with your app.
For more information on features available in Kudu, see Azure Websites online tools you should know about.
3. Mitigate the issue
Scale the app
In Azure App Service, for increased performance and throughput, you can adjust the scale at which you are running your application. Scaling up an app involves two related actions: changing your App Service plan to a higher pricing tier, and configuring certain settings after you have switched to the higher pricing tier.
For more information on scaling, see Scale an app in Azure App Service.
You can set the scaling to be Manual or Automatic.
Use AutoHeal
Restart the app
This is often the simplest way to recover from one-time issues. On the Azure Portal, on your app’s blade, you have the options to stop or restart your app.
You can also manage your app using Azure PowerShell. For more information, see Using Azure PowerShell with Azure Resource Manager.
Ошибка 502 Bad Gateway: что делать в первую очередь?
При просмотре Интернета и повторном обращении к одним и тем же ссылкам иногда может появляться сообщение: 502 Bad Gateway. Пользователь при этом не имеет возможности просмотра ресурсов выбранного Web-сайта. Обычно такое сообщение является следствием проблем, касающихся работы прокси-сервера, DNS-сервера или хостинг-сервера, где непосредственно размещается Web-сайт, который запрашивает пользователь.
С формальной точки зрения получение названного сообщения означает, что ваш браузер получил недопустимый ответ от другого сервера (или прокси-сервера) и выводит общую заставку «502 Bad Gateway», для информирования о возникшей ситуации.
Что же в таких случаях можно предпринять?
Первым делом стоит попробовать набрать в адресной строке браузера ссылку на другой Web-сайт. Лучше выбрать какой-нибудь гарантированно работающий Web-ресурс, территориально размещенный на территории, откуда вы сами получаете доступ к Интернету.
Тем самым вы можете проверить, есть ли доступ к Интернету вообще. Ведь корпоративный доступ к Интернету из локальной сети идет через прокси-сервер, а не непосредственно через модем, подключенный (или встроенный) на вашей локальной машине. Если во втором случае ошибка диагностируется более детально, то при доступе к Интернету через локальную сеть система не может диагностировать ошибку, выходящую за область выделенных ей прав. Поэтому проверять приходится косвенными методами.
Если вы обнаружили, что доступ к Интернету имеется, но ваше обращение к конкретному Web-сайту все равно дает ошибку 502, то попробуйте удалить cookies (конкретно для этого сайта или все имеющиеся) в браузере. Это делается следующим образом:
Если и это не помогло, тогда источник ошибки лежит где-то за пределами вашей сети или домашнего ПК. Возможно «упал» сервер, на который вы обращаетесь.
В этом случае «тушите свет». Придется ждать, пока «их админ прочухается».
HTTP status codes. Error 500, error 502 and more.
Any now and then, when we are browsing the internet, we get one of those – error 500 or error 404. What does this number mean? How many other numbers are there? In this article you will see the different categories of HTTP status codes, what do they say and some examples.
1?? Informational
The informational HTTP status codes show you that the request is received without problems, but you need to wait until it gets processed.
100 Continue. The server is not ready with your request. It still needs to work on it. It may be due to a large request that needs more time.
103 Early hints. The request might be too large, but you are getting some information before the final complete response.
2?? Success
Computers can show not just errors but also successes. These next codes show when a request is completed correctly.
200 OK. This message indicates a completed request. The request could be GET, HEAD, POST or TRACE.
201 Created. The request has led to the successful creation of a new resource (POST or PUT).
204 No content. The server, after processing properly your request, tells you that it won’t return any content.
3?? Redirection
If you have worked in SEO, you probably already know these redirects. They help you organize websites, especially after internal changes.
301 Moved Permanently. If somebody moves an article from one category to another, its URL will change too. You need to point the old URL to the new one.
302 Found or Moved temporarily.
The “moved temporary” has never been a popular and useful redirect. It was used like the 301, but if you move an item for just a short time.
304 Not modified. Basically what this redirect tells us is that the file we requested, has no new modification from the last time we requested it. Your computer should have it in the cache.
4?? Client Error
In a client-server model, there are two sides, the client for easy use and server which answers queries from the different users. The 4?? errors are mostly due to a problem with the client or just answer of a request.
400 error, bad request. The server says that it will not continue with the request, because of an inappropriate request (probably a syntaxes error).
401 Unauthorized. This is when the person who wants to access has failed with the authentication.
403 Forbidden. Similar to 401 error, but here there is no fail, just the user has no access to that place whatsoever.
404 Not found. The most common error, when we are searching for an old article. 404 Not found will appear when the there is no redirect and the page is just gone.
409 Conflict. The current state of the resource has a conflict that doesn’t permit the request.
5?? Server Error
Here are a few status codes that you might see often if you work with servers. This category is for the server part of the connection.
500 error – the most generic error possible. It doesn’t tell you anything more than the error is in the server.
502 error – bad gateway. The server was doing a job as a proxy or a gateway and got an invalid response from another upstream server.
503 Service unavailable. This you can see when the server gets too many task and overload or is down due to maintenance.
504 Gateway Timeout. The server, who was performing as a proxy or a gateway, didn’t receive a response in time from the upstream server. There could be a problem with the next server on the network.
Conclusion about HTTP status codes
There are even more HTTP status codes out there, but these are the most common. Now that you know what they mean, you can understand better the network and know where to search for the problem. Hope it was interesting for you, if you want to know about another code that is not in our list, put it in the comments.
Hi, I’m Martin Pramatarov. I have two degrees, a Technician of Computer Networks and an MBA (Master of Business Administration). My passion is storytelling, but I can’t hide my nerdish side too. I never forgot my interest in the Hi-tech world. I have 10 years and thousands of articles written about DNS, cloud services, hosting, domain names, cryptocurrencies, hardware, software, AI, and everything in between. I have seen the Digital revolution, the Big migration to the cloud, and I am eager to write about all the exciting new tech trends in the following years. AI and Big Data are here already, and they will completely change the world!
I hope you enjoy my articles and the excellent services of ClouDNS!
502 Bad Gateway Error
Last updated on August 10th, 2022
Any 50x error means that some request to the server didn’t return a proper result. A 502 specifically means that there was a bad gateway. At WP Engine, this gateway usually refers to the relationship between NGINX and PHP.
On the WP Engine platform, the 502 Bad Gateway error typically signals an issue between the uncached PHP processing of the request and the request being served back to the browser. Servers have a specific number of PHP Workers available to process uncached requests at any given time. If a request being processed by a PHP Worker is rejected for taking too long to complete or cannot complete, this causes the 502 Bad Gateway error.
About 502 Errors
When a 502 occurs on WP Engine this is almost always one of two things:
Before diagnosing a 502 we advise checking your access logs to confirm the 502 seen in your browser was actually returned in the access logs and not a different error code. Access logs are located in the User Portal or WordPress, by the Error Logs.
Diagnose 502 Errors
You can use your site’s error logs to see if there have been any code errors which might explain the timeout, as well as killed queries. If these logs don’t help, you can start narrowing down root causes. For example, turning off all plugins and seeing if the error still exists will help you determine if the error is caused by a plugin or by your theme.
Combating 502 errors can be an art in itself. Since the causes of these errors can be deep in the code of a site and not easily identifiable, we highly recommend consulting with a developer. If you need help finding a developer, WP Engine has a list of recommended consultants you can reference.
If you need immediate help with 502 errors please contact Support via 24/7 chat in your User Portal.
We’ve put together a helpful workflow for diagnosing 502s:
Consistent 502 Errors
Is the 502 error instant? This is most likely due to a code issue.
Is the 502 error long (
60 seconds)? This is most likely due to a process is being killed by our server timeout.
502 Errors on Specific Pages
Try disabling plugins/setting a default theme one at a time to see if the issue persists.
502 Errors at Recurring Times
Cross-check the timing of the cron jobs that are receiving the 502 errors
Cross-check your traffic peaks times and review any cache exclusions you’ve requested via Support
Random 502 Errors
Your database may be the issue, try optimizing your database.
Is object caching enabled? Try disabling the object cache.
Prevent 502s
The best way to prevent issues with 502 Bad Gateway errors is to ensure your site is healthy. Following WordPress best practices for site health will help prevent code conflicts and keep your site secure.
Simple steps like updating your Plugins, Themes, and WordPress itself can help ensure site health. These updates should be tested in a staging or test environment first to prevent code conflicts on your production site.
Last, you should regularly audit your plugins and settings to delete anything unnecessary. Fewer installed plugins means a smaller codebase to maintain and fewer opportunities for code conflicts.
Disable Server Timeout
The 60-second timeout is in place to ensure our servers are able to serve the maximum amount of concurrent requests. Without a timeout in place, we’ve seen requests take minutes to even hours to complete. With the continued performance of your site in mind, we will not be able to disable the server timeout which may be causing your 502s. This timeout is programmed at the root of our platform. It is in place to ensure optimal server health, speed, and uptime.
Join the 1.2M websites that trust WP Engine as their WordPress host.
Which HTTP status code to use upon remote server failure? 500 or 502?
I have an API that, upon a client’s POST request:
In other words, normal web server stuff.
From the RFC 7231,
In one hand, the 502 Bad Gateway looks like this is intended for «dumb» servers that just forwards the request to the remote server, and returns its response to the client, without much processing.
1 Answer 1
To address your specific points.
In one hand, the 502 Bad Gateway looks like this is intended for «dumb» servers that just forwards the request to the remote server, and returns its response to the client, without much processing.
It’s all convention of course, but I’d say you’re reasonably correct in this analysis.
In the other hand, to not be able to access the remote server doesn’t sound like a 500 Internal Server Error. more like a «Remote Server Error».
I’d argue it’s still an internal server error, just an internal server error that’s been caused by a remote server somewhere else (and that is a detail your users arguably don’t need to know.)
Что значит эта ошибка. 502 Bad Gateway.
При просмотре Интернета и повторном обращении к одним и тем же ссылкам иногда может появляться сообщение: 502 Bad Gateway. Пользователь при этом не имеет возможности просмотра ресурсов выбранного Web-сайта. Обычно такое сообщение является следствием проблем, касающихся работы прокси-сервера, DNS-сервера или хостинг-сервера, где непосредственно размещается Web-сайт, который запрашивает пользователь.
С формальной точки зрения получение названного сообщения означает, что ваш браузер получил недопустимый ответ от другого сервера (или прокси-сервера) и выводит общую заставку «502 Bad Gateway», для информирования о возникшей ситуации.
Что же в таких случаях можно предпринять?
Первым делом стоит попробовать набрать в адресной строке браузера ссылку на другой Web-сайт. Лучше выбрать какой-нибудь гарантированно работающий Web-ресурс, территориально размещенный на территории, откуда вы сами получаете доступ к Интернету.
Тем самым вы можете проверить, есть ли доступ к Интернету вообще. Ведь корпоративный доступ к Интернету из локальной сети идет через прокси-сервер, а не непосредственно через модем, подключенный (или встроенный) на вашей локальной машине. Если во втором случае ошибка диагностируется более детально, то при доступе к Интернету через локальную сеть система не может диагностировать ошибку, выходящую за область выделенных ей прав. Поэтому проверять приходится косвенными методами.
Если вы обнаружили, что доступ к Интернету имеется, но ваше обращение к конкретному Web-сайту все равно дает ошибку 502, то попробуйте удалить cookies (конкретно для этого сайта или все имеющиеся) в браузере. Это делается следующим образом:
Если и это не помогло, тогда источник ошибки лежит где-то за пределами вашей сети или домашнего ПК. Возможно «упал» сервер, на который вы обращаетесь.
В этом случае «тушите свет». Придется ждать, пока «их админ прочухается».
Request failed with status code 502
Все, кто относительно часто занимается интернет-серфингом, периодически сталкивались с белой страницей, на которой виднелась табличка «502 bad gateway» и прочие непонятные слова. Что это значит, как исправить и принесет ли подобное известие вред ПК?
Дабы заранее успокоить потенциальных паникеров, никакого вреда системе ошибка не наносит, поскольку проявляется со стороны сервера, а не пользователя. Причин этому может быть несколько:
Понятно, что большинству эти термины ничего не скажут, но будем объяснять на пальцах: ошибка 502 говорит о том, что сервер, на котором находится сайт с ВК, одноклассниками, Яндексом и прочими сервисами (для каждого ресурса свой сервер) в данный момент не работает. Как исправить проблему, чтобы точно убедиться, что ошибка не с вашей стороны? Да все элементарно.
Для начала откройте какой-либо другой ресурс. Все открылось? Значит проблема с одним сайтом. Ошибка повторилась? Ситуация более запущена, но решаема. Кстати, перевод «Bad Gateway» звучит как «плохой шлюз».
Пути устранения
В первую очередь сделайте самое элементарное, что делают в таких случаях – почистите лишние данные браузера, а именно кэш и cookie-файлы. В большинстве случаев проблема должна решиться. К слову, это касается как обычных, так и корпоративных пользователей, которые выходят в интернет через локальную сеть с помощью хитрых манипуляций админов.
Разберем процедуру на примере Google Chrome.
Жмем на пункт «История», а затем кликаем по кнопке «очистить».
Появится поле, в котором нужно выставить/убрать нужные флажки, дабы лишнего не подчистить.
Выберите интервал «за все время», чтобы удалить максимальное количество ненужной информации. Остается только дождаться конца операции и повторить попытку. Не работает? Тогда проблема точно не на вашем ПК. Ну а вы дополнительно удалили лишний мусор из системы.
Причины возникновения
Рассмотрим варианты возникновения этой злополучной 502 ошибки. Эта информация будет полезна скорее тем, кто держит сервер с сайтом, хотя последние и так знают причину. Однако для расширения кругозора неплохо бы и почерпнуть эти знания.
Итак, если сервер рассчитан на 5-7 тысяч запросов в секунду (такое количество народа одновременно зашло на ресурс), а подобных запросов переваливает за 10 тысяч, то ошибка проявится очень скоро. В таких случаях нужно наращивать мощность сервера, увеличивая канал и добавляя память. Вы должны понимать, что типичный домашний ПК в принципе не создан на столь высокую нагрузку, создаваемую на процессор извне. Отсюда и различие между «серверными» и «обычными» машинами.
Второй вариант – DDoS-атака на сервер. По сути, разновидность перегруженности, только в этот раз она намеренная. Конкурирующая организация специально заваливает своего визави запросами, которые последний просто не в силах обработать, в результате чего система намертво виснет и «падает». Таким образом, наносятся огромные убытки той компании, на которую была произведена атака.
Не нужно заваливать оператора поддержки глупыми вопросами из серии «а когда заработает?». Сначала проверьте сервис на другом ПК или смартфоне. Если и там не работает – ждите. И на всякий случай почистите cookie, хуже точно не будет.
Источники:
- http://pro-promotion.ru/articles/seo/oshibka-502-chto-eto-znachit-i-kak-ispravit
- http://www.ionos.com/digitalguide/hosting/technical-matters/what-does-502-bad-gateway-mean-explanation-and-solution/
- http://docs.microsoft.com/ru-ru/azure/app-service/troubleshoot-http-502-http-503
- http://hoster.ru/articles/chto-takoe-oshibka-502-bad-gateway-i-kak-ee-ispravit
- http://tehnopub.ru/502-bad-gateway/
- http://kokoc.com/blog/oshibka-502-bad-gateway-chto-eto-znachit-i-kak-ispravit/
- http://docs.microsoft.com/en-us/iis/extensions/troubleshooting-application-request-routing/troubleshooting-502-errors-in-arr
- http://solutics.ru/internet-i-set/502-oshibka-shlyuza/
- http://strana-it.ru/502-bad-gateway/
- http://handyhost.ru/help/term/chto-znachit-oshibka-502.html
- http://webmastermix.ru/domains-and-hostings/299-oshibka-502-bad-gateway-prichiny-vozniknoveniya-i-sposoby-ustraneniya.html
- http://aydasite.ru/oshibka-502-bad-gateway-chto-znachit-kak-ispravit/
- http://spayte.livejournal.com/2246857.html
- http://docs.microsoft.com/en-us/iis/troubleshoot/diagnosing-http-errors/troubleshooting-http-5022-bad-gateway-error-in-cgi-applications
- http://www.section.io/blog/504-503-errors-difference/
- http://geek-nose.com/oshibka-502-bad-gateway-chto-eto-znachit-i-kak-ee-reshit/
- http://os-helper.ru/oshibki/502-bad-gateway-nginx-chto-eto-znachit.html
- http://windowserror.ru/obshhie/oshibka-502/
- http://stackoverflow.com/questions/62831833/http-request-fails-with-response-status-code-502
- http://github.com/axios/axios/issues/2802
- http://19216811.ru/error-502
- http://docs.microsoft.com/en-us/azure/application-gateway/application-gateway-troubleshooting-502
- http://github.com/MicrosoftDocs/iis-docs/blob/main/iis/extensions/troubleshooting-application-request-routing/troubleshooting-502-errors-in-arr.md
- http://itigic.com/ru/error-502-bad-gateway-what-causes-it-and-how-to-fix-it/
- http://www.wpoven.com/blog/need-know-502-error-bad-gateway/
- http://stackoverflow.com/questions/48266604/unable-to-start-process-c-program-files-dotnet-dotnet-exe-the-web-server-reque
- http://www.allconnect.com/blog/502-bad-gateway-error-explained
- http://otvet.mail.ru/question/91144937
- http://github.com/knadh/listmonk/issues/128
- http://github.com/kubeapps/kubeapps/issues/1164
- http://www.ionos.co.uk/digitalguide/hosting/technical-matters/what-does-502-bad-gateway-mean-explanation-and-solution/
- http://otvet.mail.ru/question/37010431
- http://stackoverflow.com/questions/5011632/should-a-502-http-status-code-be-used-if-a-proxy-receives-no-response-at-all
- http://forum.mybb.ru/viewtopic.php?id=13802
- http://stackoverflow.com/questions/38346847/nginx-docker-container-502-bad-gateway-response
- http://www.keycdn.com/support/502-bad-gateway
- http://timeweb.com/ru/community/articles/chto-znachit-oshibka-servera-503-i-kak-ee-ispravit
- http://www.howtogeek.com/356389/what-is-a-502-bad-gateway-error-and-how-can-i-fix-it/
- http://medium.com/swlh/troubleshoot-elastic-load-balancer-http-502-bad-gateway-errors-28a32d4e0acb
- http://www.bolshoyvopros.ru/questions/1098444-oshibka-502-bad-gateway-kak-ee-ispravit-chto-delat.html
- http://github.com/openvinotoolkit/cvat/issues/3948
- http://neoshibka.ru/oshibka-502-bad-gateway-kak-ispravit/
- http://hosting101.ru/502-bad-gateway-nginx.html
- http://docs.microsoft.com/ru-ru/azure/application-gateway/application-gateway-troubleshooting-502
- http://bobcares.com/blog/webhook-502-error/
- http://webpop.io/cloudflare/502-bad-gateway-error/
- http://stackoverflow.com/questions/40598428/ngrok-errors-502-bad-gateway
- http://wifigid.ru/poleznoe-i-interesnoe/http-500-error
- http://github.com/expo/expo-cli/issues/2300
- http://techblog.sdstudio.top/kak-ispravit-oshibku-502-bad-gateway-v-wordpress/
- http://blog.hubspot.com/marketing/502-bad-gateway
- http://docs.microsoft.com/en-us/azure/app-service/troubleshoot-http-502-http-503
- http://www.blogs.pcmag.ru/node/601
- http://www.cloudns.net/blog/http-status-codes-error-500-error-502/
- http://wpengine.com/support/troubleshooting-502-error/
- http://stackoverflow.com/questions/50101598/which-http-status-code-to-use-upon-remote-server-failure-500-or-502
- http://otvet.mail.ru/question/54523815
- http://h-y-c.ru/knowledge-base/internet/other/272-502-bad-gateway-chto-ehto-znachit.html