Nginx выдает ошибку 502

Опубликовано: вторник, 4 апреля 2023 г. в 20:32

  • DevOps

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

Поддерживать сервер сложно.

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

Одной из таких распространённых ошибок на серверах Nginx является 502 Bad Gateway.

Nginx Ошибка 502 Bad Gateway

Сообщение об ошибке загадочно.

Итак, многие веб-мастера засучивают рукава и смотрят error.log:

2017/04/04 08:34:43 [error] 949#949: *7 connect() failed (111: Connection refused) while connecting to upstream, client: XXX.XXX.XXX.XXX, server: myserver.com, request: "GET /myurl-this/ HTTP/1.0", subrequest: "/redis-fetch", upstream: "redis://127.0.0.1:6379", host: "refserver.com", referrer: "http://referalsite.com/myurl-this/"

Да, ещё больше непонятного…

Вы понимаете, что что-то напутано, потому что он сообщает failed (сбой) и refused (отказ).

Но что это означает?

Вот решение. Мы перечислили пять основных причин возникновения ошибки Nginx 502 Bad Gateway и способы их решения.

Сбой серверной службы

Nginx зависит от серверных служб, таких как PHP-FPM, служб баз данных и серверов кэша для запуска веб-приложений.

Таким образом, если какой-либо из этих сервисов выйдет из строя или зависнет, Nginx не получит никаких данных, что приведёт к ошибке 502 Bad Gateway.

Службы, которые, как мы видели, сбоили — это:

  • PHP-FPM
  • Apache
  • Cache
  • Database

Причины сбоя службы могут варьироваться от всплесков трафика и ограничений ресурсов до ошибок диска и DDoS-атак.

Если вы подозреваете, что серверная служба не отвечает или вышла из строя, попробуйте завершить все не отвечающие процессы и перезапустить службу.

Например, вот один из способов убить нефункционирующие процессы PHP-FPM и перезапустить службу.

$ kill -9 $(pgrep php-fpm)
$ /etc/init.d/php-fpm restart
* Restarting PHP FastCGI Process Manager php-fpm [ OK ]

Внимание: Не запускайте эти команды, если не знаете, как они работают.

Если перезапуск службы не сработал, возможно, вам придётся попросить кого-нибудь более внимательно изучить состояние сервера.

Высокая нагрузка на сервер

Вторая наиболее распространённая причина ошибки Nginx 502 Bad Gateway является высокая средняя загрузка серверов.

Всплески нагрузки приводят к тому, что службы не отвечают. Мы видели следующие причины скачков нагрузки:

  • Внезапный всплеск посещаемости сайта (может быть сезонным или маркетинговым/рекламным).
  • Заражение вредоносным программным обеспечением (вирусы/трояны/майнеры/сканеры и т.д.) на сервере.
  • Рассылка спама в комментариях или использование других уязвимостей.
  • Брут форс атаки на веб-приложения.
  • Ошибки приложений, вызывающие утечку памяти или перегрузку ресурсов.

Для устранения проблем с высокой нагрузкой, сначала необходимо выяснить, какой ресурс используется (ввод/вывод, память, процессор или сеть).

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

Неправильная конфигурация сервиса

Сервер Nginx и серверные службы зависят от многих подсистем. Таких, как DNS resolver, процессы Apache, службы PHP, сервер базы данных и т.д. Если даже одна из этих служб имеет неправильную конфигурацию, эта служба не сможет ответить, и Nginx покажет ошибку 502 Bad Gateway.

Проблемы с конфигурацией, с которой мы сталкивались:

  • DNS resolver неправильно настроен в Nginx, что приводит к сбою поиска домена.
  • Данные логина БД настроены неправильно после недавней миграции, восстановления или обновления.
  • Синтаксическая ошибка настроек брандмауэра Apache (mod-security), вызывающая сбой Apache.
  • Для приложений PHP установлены неправильные ограничения памяти или файлов.
  • Ограничения пропускной способности (например, количество подключений на IP-адрес) установлены слишком строго, что приводит к сбою легальных посетителей.
  • …и многое другое.

Не существует простого способа обнаружения ошибки конфигурации. Вам нужно просмотреть error.log и обратить внимание на то, что написано об ошибке.

Например, эта ошибка сообщает, что приложение PHP достигло максимально допустимого предела процессов (определяемого параметром pm.max_children).

WARNING: [mysite.com] server reached max_children setting (30), consider raising it
ERROR: unable to read what child say: Bad file descriptor (9)

Если вы не знакомы с PHP или настройками веб-сервера, лучше всего обратиться к администратору сервера.

Порт сервиса заблокирован в брандмауэре

Брандмауэры/файрволлы — основа безопасности сервера. Но если их неправильно настроить, это может привести к блокировке запросов или сбою служб.

Например, на серверах Linux, на которых работает пакет автоматизации Plesk, Nginx работает на 80 порту, а Apache на 7080. Но брандмауэры/файрволлы по умолчанию блокируют необычные порты, и это приведёт к том, что Nginx не сможет подключиться к Apache.

Результат? Ошибка 502 Bad Gateway.

Такие проблемы часто возникают при включении новой службы (например, кэширующий сервис, Ruby, и т.д.) в бэкенде, во время миграции или после обновления сервера.

Чтобы исправить это, мы смотрим, на каком порту работает каждая служба с помощью следующей команды:

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

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

Ошибки веб-приложений

Редким случаем ошибки 502 Bad Gateway является ошибка приложения.

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

[notice] child pid 27831 exit signal Segmentation fault (11)

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

Итог

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

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

И необязательно чтобы вы использовали Nginx в качестве прокси для доступа к сети. Нет, для работы большинства сайтов требуется генерация динамического контента, например, на php. Поэтому Nginx часто выступает в прокси для Apache или php-fpm. В этой статье мы рассмотрим что означает 502 bad gateway Nginx, как исправить ее.

Как и следует из названия, эта ошибка значит, что Nginx попытался связаться со шлюзом и у него ничего не вышло. Например, запросы от пользователей принимает Nginx, поскольку он работает быстро и потребляет мало ресурсов, а за генерацию контента отвечает php-fpm. Если сервис php-fpm во время обработки запроса получил какую-либо ошибку и не вернул результата, или же он вообще отключен и Nginx не может получить к нему доступ мы получим такую ошибку.

Вот основные причины:

  • Nginx используется в качестве прокси для Apache или php-fpm, но эти сервисы не запущены;
  • Nginx используется качестве прокси для php-fpm, но параметры доступа к сокету неверно настроены;
  • Неверно настроены значения размера буфера и таймаута для php-fpm в nginx.conf;
  • Ошибки в конфигурации Nginx.

Как исправить ошибку 502 bad gateway Nginx

1. Анализ логов и перезапуск

Чтобы исправить ошибку нужно выяснить что случилось со шлюзом. Лучший способ сделать это — посмотреть логи Nginx, там обязательно должно быть что-то написано и намного подробнее, чем в выводе браузера:

tail -f /var/log/nginx/error.log

Это уже должно дать вам некоторые подсказки что делать дальше. Еще в первую очередь не помешает проверить файл конфигурации Nginx на ошибки:

nginx -t

Допустим, у нас в качестве шлюза для генерации динамического содержимого используется php-fpm. Тогда нужно проверить запущен ли вообще этот сервис:

ps aux | grep php

Если все процессы уже запущены, попробуйте перезапустить их с помощью systemd:

sudo systemctl restart php-fpm

Если процесс остановлен, то его нужно запустить:

sudo systemctl start php-fpm

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

sudo tail -f /var/log/php7.0-fpm.log

Но если такой рецепт не помог, и ошибка 502 bad gateway nginx нужно идти дальше. Внимательно пересмотрите лог, возможно, там уже есть ответ.

2. Доступность php-fpm и владелец

Также эта ошибка может возникать при проблемах доступа к файлу сокета php-fpm, например, когда этот файл называется по другому или для него выставлены неверные права. Сначала убедитесь, что в конфигурационном файле /etc/nginx/nginx.conf указан правильный адрес файла сокета php-fpm:

location ~ .php$ {
fastcgi_pass unix:/var/run/php7.0-fpm.sock;
include fastcgi_params;
}

Файл /var/run/php7.0-fpm.sock должен действительно существовать в файловой системе. Дальше нужно убедиться, что у сокета правильный владелец, это должен быть тот же пользователь, от имени которого запускается Nginx, группа тоже должна соответствовать. Откройте файл /etc/php7.0/fpm/pool.d/www.conf и найдите строчки user и group. Они должны иметь такое же значение, как строчка user в конфиге nginx.conf:

listen = /var/run/php7.0-fpm.sock
listen.owner = www-data
listen.group = www-data

После того как выставите правильные параметры, перезапустите сервисы:

sudo service php5-fpm restart
$ sudo service nginx restart

3. Время отклика и размер буфера

Возможно, размер буфера и время ожидания ответа от fastcgi настроены неверно и программа просто не успевает обработать большой запрос. Попробуйте увеличить такие параметры в /etc/nginx/nginx.conf. Если таких строк не существует, добавьте их в блок http, как здесь:

sudo vi /etc/nginx/nginx.conf

http {
...
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
...
}

Выводы

В этой статье мы рассмотрели 502 bad gateway nginx что это значит и как исправить эту ошибку. Как видите, может быть достаточно много причин ее возникновения, но решить все достаточно просто если внимательно посмотреть логи и понять в чем там действительно проблема. Надеюсь, информация была полезной для вас.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

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

Что означает ошибка 502 Bad Gateway

Ошибки, принадлежащие серии 5xx, означают появление проблем на стороне сервера. Если взять конкретно ошибку 502 Bad Gateway, то ее появление будет означать получение неправильного ответа сервера. «Виновниками» в такой ситуации обычно являются прокси, DNS или хостинг-серверы.

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Что делать, если вы пользователь

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

Перезагрузить страницу

Возможно, на момент загрузки число запросов на сайт превышает определенный лимит, устанавливаемый владельцем сайта. Если это действительно так, тогда простая перезагрузка страницы вполне будет уместна. Я рекомендую обновить страницу как минимум три раза в течение 2-3 минут и только потом приступать к следующим способам.

Проверить подключение к интернету

Стоит проверить работу модема и попробовать загрузить другие страницы. Убедитесь, что подключение к интернету стабильное. Еще вариант – перезапустить маршрутизатор и попробовать снова загрузить проблемный сайт.

Очистить кэш и cookies

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

Для любого браузера актуально – зайти в историю просмотров и найти ссылку «Очистить историю». В новом окне отметить пункты с кэшем и cookies, затем подтвердить действие. Как только данные будут удалены, надо вновь попробовать загрузить страницу. Не помогло? Идем дальше!

Очистить кэш DNS

Допустимо, что в кэше установлено неправильное значение IP-адреса. Для таких случаев можно использовать сброс DNS кэша. В ОС Windows необходимо открыть инструмент «Командная строка» (вводим в поисковую строку название программы и выбираем запуск от имени администратора).

Далее следует ввести вот такую команду и активировать ее нажатием на клавишу Enter:

ipconfig /flushdns

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

Как очистить кэш DNS через командную строку Windows

Для Linux действие примерно схоже, но команда выглядит иначе. Открываю утилиту «Терминал» и ввожу в поле вот такой запрос:

Для Ubuntu:

sudo service network-manager restart

Для других дистрибутивов:

sudo /etc/init.d/nscd restart

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

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

Отключить плагины и расширения

На загрузку некоторых страниц могут влиять установленные в браузер плагины и расширения. Особенно это касается VPN-сервисов и блокировщиков рекламы. Попробуйте поочередно отключать их и перезапускать страницу. Не исключено, что виновник будет найден.

Зайти на страницу позже

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

Читайте также

Ошибка 400 Bad Request

Что такое ошибка 500 и когда она возникает

Что делать, если вы администратор сайта

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

Проверка журнала ошибок

Актуально в случаях, при которых ошибка 502 Bad Gateway появляется после внесения изменений или обновления. Определить это очень просто, нужно лишь проверить журнал ошибок. В CMS WordPress можно включить запись возникающих ошибок, добавив в файл wp-config.php вот такие строки:

define( 'WP_DEBUG', true );

define( 'WP_DEBUG_LOG', true );

define( 'WP_DEBUG_DISPLAY', false );

После этого все записи начнут отображаться в файле debug.log. Храниться он будет в директории wp-content. Понадобится некоторое время, чтобы причины ошибок были записаны. Потом можно тщательно изучить записи и уже на основе их предпринимать конкретные изменения.

Проверка плагинов

Следует проверить, не влияют ли какие-либо плагины на работу сайта. Для этого можно поочередно отключать их, просто переименовывая папку интересующего плагина. Для этого надо выделить папку, затем нажать на меню «Файл» и в нем выбрать пункт «Переименовать».

Отключение плагина в WordPress путем переименования папки

Проверка сети CDN

Сети CDN и службы предотвращения DoS тоже могут влиять на работу сайта. Обычно виновник проблемы указывается на странице с кодом ошибки. Например, если под кодом 502 Bad Gateway есть строка cloudflare-nginx, значит, для исправления ошибки надо обратиться в службу поддержки CloudFlare. Можно отключить данный сервис, но потом придется долго ждать обновления DNS (это может занять несколько часов).

Один их вариантов отображения ошибки 502 Bad Gateway

Ошибка 502 на виртуальном хостинге VPS/VDS

Ошибка 502 Bad Gateway возникает из-за превышения лимита трафика пользователей, «шалостей» бота, скачивания сайта или даже DoS‑атаки. Решение данной проблемы кроется в ограничениях памяти.

Запустить команду top

Данный запрос в терминале поможет установить наличие свободной памяти. Этим же способом можно проверить, работает ли Apache.

Посмотреть логи Apache и nginx

Обычно в этих логах отображается активность пользователей. Если есть что-то подозрительное, можно предпринять действия. К примеру, забанить определенные IP-адреса, настроить Fail2ban или подключить систему защиты от DoS-атак.

Если после этого количество запросов к серверу снизилось, необходимо перезапустить Apache.

Увеличить объем памяти

Бывает, что с логами все нормально, но памяти на обработку запросов все равно не хватает. Узнать об этом просто – при проверке командой top будет выдана ошибка OOM (out of memory). В таких случаях можно просто увеличить ее объем. Можно просто заказать другой тариф, в котором количество предоставляемой памяти больше. Подробнее об этом.

Проверить лимиты на php-cgi процессы

Если после проверки командой top показано, что свободной памяти еще достаточно, значит, на php-cgi процессы установлены лимиты. Для решения надо открыть конфигурационный файл Apache – httpd.conf, найти секцию модуля FastCGI (mod_fascgi или mod_fastcgid) и увеличить лимит.

Обратиться к службе технической поддержки

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

A 502 Bad Gateway Nginx error is an HTTP status code that represents a server acting as a gateway or proxy server failing to receive a valid response from an upstream server. In the case of Nginx, a 502 bad gateway error occurs when the server cannot establish a connection with the upstream server or when the upstream server returns an invalid response.

This error is commonly seen when trying to access a website or web application that is hosted behind a reverse proxy or load balancer.

There are multiple variations of 502 Bad gateway Nginx Error you might find on different sites. For example:

  • HTTP Error 502- Bad Gateway
  • 502 Proxy Error
  • 502 Bad Gateway
  • 502 Service Temporarily Overloaded
  • HTTP 502
  • 502 Bad Gateway NGINX
  • Error 502

Nginx is a well-known open-source web server that is highly popular for its performance, scalability, and flexibility. However, similar to other web servers, Nginx can face errors that hinder its ability to deliver content to clients. One such error is the 502 Bad Gateway Nginx error.

Encountering errors can be quite frustrating and confusing, especially if you are not technically proficient. You may come across several similar prominent errors, such as the white screen of death, and the error establishing database connection. But 502 bad gateway nginx error is a very popular one.

There can be multiple possible reasons for this error to happen and therefore different ways to troubleshoot it. In this post, we will tell you what 502 bad gateway Nginx really means, its possible causes and what are the best troubleshooting method you must follow.

Let us get started!



Read: 🚩 15 Methods to Fix 502 Bad Gateway Error on Your Website


What Causes a 502 Bad Gateway Nginx Error?

There can be several reasons why a 502 Bad Gateway error may occur in Nginx, but here are some of the most common ones listed down below:

Server Overload

When a backend server receives too many requests, it can become overloaded and fail to respond within the timeout period. This causes a 502 error as the upstream server cannot fulfill the client’s request. Proper server sizing, resource allocation, load balancing, and scaling strategies can prevent server overload.

Connectivity Issues

  • Connectivity issues can cause a 502 Bad Gateway error in Nginx when there is a problem with the network connection between the reverse proxy server and the backend server.
  • This can happen due to network congestion, misconfigured network settings, or hardware failures.
  • When the reverse proxy server attempts to forward a request to the backend server but cannot establish a connection, it returns a 502 error to the client.
  • The error occurs because the reverse proxy server acts as an intermediary between the client and the backend server and is unable to connect to the backend server to fulfill the client’s request.
  • Troubleshooting network settings, checking firewall rules, and monitoring network traffic can help fix the issue.

DNS Issues

  • DNS issues can cause a 502 Bad Gateway error in Nginx when the DNS resolution for the backend server fails.
  • This can happen due to incorrect DNS configurations, DNS server failures, or DNS caching issues.
  • When a client sends a request to the reverse proxy server, the reverse proxy server needs to resolve the domain name of the backend server to an IP address.
  • If the DNS resolution fails, the reverse proxy server cannot forward the request to the backend server, resulting in a 502 error being returned to the client.

Read: 🚩 What is DNS?


Firewall Restrictions

  • Firewall restrictions can cause a 502 Bad Gateway error in Nginx when a firewall blocks the connection between the reverse proxy server and the backend server.
  • This can happen when the firewall is configured to restrict traffic to and from specific IP addresses or ports.
  • When the reverse proxy server attempts to connect to the backend server, but the firewall blocks the connection, it returns a 502 error to the client.
  • This occurs because the reverse proxy server acts as an intermediary between the client and the backend server and cannot establish a connection with the backend server to fulfill the client’s request.
  • To fix firewall-related issues causing a 502 error, you may need to adjust firewall rules to allow traffic to flow between the reverse proxy and backend servers.

Software Bugs

  • A 502 Bad Gateway error may occur due to a software bug or misconfiguration in the reverse proxy server or backend server.
  • This error can happen because of coding errors or misconfigurations of server modules or applications.
  • If the software or configuration of either server contains a bug, it may fail to handle requests or respond within the timeout period, resulting in a 502 error being returned to the client.
  • To fix software-related issues causing a 502 error, you may need to examine the logs of both the reverse proxy and backend servers to identify any errors or warning messages.

PHP-FMP is Taking too long to respond

  • PHP-FPM (FastCGI Process Manager) can cause a 502 Bad Gateway error in Nginx when it fails to respond within the timeout period or encounters a critical error.
  • This error can happen due to insufficient resources, misconfiguration, or a bug in the PHP code.
  • PHP-FPM is a popular way of running PHP applications in Nginx, where Nginx sends the request to PHP-FPM and it processes the PHP code and returns the result to Nginx, which then sends the response back to the client.
  • To fix PHP-FPM-related issues, you may need to adjust the PHP-FPM configuration to increase the number of processes or threads or adjust the timeout settings.
  • You may also need to examine the PHP code to identify and fix any bugs or performance issues.
  • Additionally, monitoring the server logs and system resources can help identify any patterns or trends that could indicate a larger issue with PHP-FPM.

Read: 🚩 How to Fix HTTP 504 Gateway Timeout Error?


How to Fix a 502 Bad Gateway Nginx?

Here are some best solutions that you can follow to fix a 502 Bad Gateway Nginx error:

  • Check the status of Nginx
  • Check Backend Server Status
  • Check the DNS configuration
  • Check the Firewall Configuration
  • Increase the Buffer Size
  • Restart Nginx Server
  • Check PHP-FPM status

Check the status of Nginx

The first thing you need to do is to check whether Nginx is running and responding to requests or not. To do that, run the following command given below:

systemctl status nginx

If the Nginx is running, you will get an output message something like this,

nginx.service - The nginx HTTP Server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2022-10-11 10:25:41 UTC; 1 days ago
Docs: https://httpd.nginx.org/docs/2.4/

If the Nginx is not running, you will get an output message something like this,

nginx.service - The nginx HTTP Server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Fri 2022-10-11 10:25:41 UTC; 25s ago
Docs: https://httpd.nginx.org/docs/2.4/

Now, in case the Nginx is not running, you have to start it again by using the following command,

systemctl start nginx

Check Backend Server Status

  • Log in to the reverse proxy server that is hosting Nginx.
  • Open a terminal window and run the following command:

curl -I http://backend-server-ip-address/

• Replace “backend-server-ip-address” with the IP address of your backend server.

• Check the HTTP status code in the output of the command. If the backend server is running correctly, you should see a status code of 200 OK.

• If you receive a status code other than 200, it indicates that there may be an issue with the backend server. You can further investigate the issue by examining the logs of the backend server to identify any errors or warning messages.

Check the DNS configuration

If the DNS resolution fails, the reverse proxy server cannot forward the request to the backend server, resulting in a 502 Bad Gateway error being returned to the client. Therefore, it is important to verify that the DNS configuration for the backend server is correct.

To check the DNS configuration, you can perform the following steps:

  • Log in to the reverse proxy server that is hosting Nginx.
  • Open a terminal window and run the following command:

nslookup backend-server-domain-name

Replace “backend-server-domain-name” with the domain name of your backend server.

• Check the output of the command to verify that the correct IP address is returned for the backend server.

  • If the output of the command indicates that the DNS resolution failed, there may be an issue with the DNS configuration. You can further investigate the issue by checking the DNS settings for the domain name of the backend server, or by contacting your DNS provider for assistance.

Check the Firewall Configuration

It is advised to check the firewall logs for an unusual block. Sometimes Firewalls also prevent or block sites. To overcome this issue, you need to temporarily disable your firewalls and check whether the issue persists or is resolved.

Increase the Buffer Size

Increasing the buffer size allows Nginx to store more data from the server’s response, ensuring that the response is complete and error-free. To increase the buffer size, you need to edit the Nginx configuration file and add the following directives.

  • proxy_buffer_size: Sets the size of each buffer. The default value is usually 4K. You can increase it to a higher value depending on your server’s requirements. For example, to set the buffer size to 16K, add the following line to your configuration file:

proxy_buffer_size 16k;

  • proxy_buffers: Sets the number of buffers to allocate. The default value is usually 8. You can increase it to a higher value depending on your server’s requirements. For example, to set the number of buffers to 32 and the buffer size to 16K, add the following line to your configuration file:

proxy_buffers 32 16k;


Note: It’s important to note that increasing the buffer size and number of buffers will increase memory usage on the server. So, you should experiment with different buffer sizes and buffer numbers to find the optimal setting for your server and application.


  • After making changes to the Nginx configuration file, save the file and restart Nginx for the changes to take effect. You can do this by running the following command:

sudo service nginx restart

Restart Nginx Server

In some cases, just restarting the Nginx server may resolve the 502 bad gateway Nginx error. To do this,

You need to run a command in your terminal or shell. The exact command depends on the operating system and distribution you are using, but here are a few examples:

  • Ubuntu and Debian:

sudo service nginx restart

  • CentOS, Fedora, and RHEL:

sudo systemctl restart nginx

  • macOS:

sudo nginx -s reload

These commands will gracefully restart the Nginx server, meaning that it will wait for any active connections to finish before shutting down and starting again.

Check PHP-FPM status

Sometimes, the 502 Bad Gateway Nginx error can also be triggered by PHP-FPM not running. Therefore, it is necessary to check the status of PHP-FPM to ensure it is running properly.

To check the running status, you can use the following command,

sudo service php-fpm status

If PHP-FPM is running, you should see a message stating that it is active.

However, in case PHP-FPM is not running, you can try restarting it using the following command:

sudo service php-fpm restart

This command will restart the PHP-FPM service, which can help resolve any issue that might be triggering a 502 bad gateway Nginx error.


Summary

A 502 Bad Gateway Nginx error is a common error that Nginx users may encounter. It is typically caused by connectivity issues, server overload, DNS issues, firewall restrictions, or software bugs.

However, following the steps outlined in this article, you can troubleshoot and resolve a 502 bad gateway nginx error.

If none of the above methods have worked for you, unfortunately, consider seeking assistance from Nginx forums or a highly experienced and qualified Nginx consultant.

If you have any tips or suggestions regarding the 502 Bad Gateway Nginx error that we may have missed in this post or if you would like to share your experience with the same, please let us know in the comment section below. We welcome your input.


Read: 🚩 How to fix HTTP 500 Internal Server Error in WordPress?


Frequently Asked Questions

How do I fix 502 Bad gateway nginx?

You can fix 502 Bad Gateway nginx error by following the below methods:
1. Check the status of Nginx
2. Check Backend Server Status
3. Check the DNS configuration
4. Check the Firewall Configuration
5. Increase the Buffer Size
6. Restart Nginx Server
7. Check PHP-FPM stat

How do I check my nginx status?

To check the nginx status, Run the following command given below:
systemctl status nginx
The Output will show whether the nginx is running or not.

What is a 502 Bad gateway error?

A 502 Bad Gateway Nginx error is an HTTP status code that represents a server acting as a gateway or proxy server failing to receive a valid response from an upstream server.

Maintaining a server is hard.

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

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

502 bad gateway Nginx

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

The error message is cryptic.

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

2017/04/04 08:34:43 [error] 949#949: *7 connect() failed (111: Connection refused) while connecting to upstream, client: XXX.XXX.XXX.XXX, server: myserver.com, request: "GET /myurl-this/ HTTP/1.0", subrequest: "/redis-fetch", upstream: "redis://127.0.0.1:6379", host: "refserver.com", referrer: "http://referalsite.com/myurl-this/"

Yeah, more gibberish.

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

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

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

1. Backend service failed

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

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

Some services that we’ve seen to fail are:

  • PHP
  • Apache
  • Cache
  • Database

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

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

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

# kill -9 $(pgrep php-fpm)
# /etc/init.d/php-fpm restart
* Restarting PHP FastCGI Process Manager php-fpm        [ OK ]

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

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

Our Nginx experts are online 24/7. Click here if you need help resolving your server error.

2. High server load

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

Load spikes cause services to not respond.

We’ve seen these reasons for load spikes:

  • Sudden spike in website traffic (can be seasonal or marketing / promotional).
  • Malware infection on the server.
  • Comment spamming or other vulnerability exploits.
  • Brute force attacks that’s designed to exploit web apps.
  • Application bugs that cause memory leaks or resource hogging.

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

The we find out which service is abusing that resource, and from that point, find out which user in that service owns the abusive script or software.

Click here to know more about high load troubleshooting.

If your server is currently under high load, and you need urgent help, click here to contact our Emergency Server Support techs. We are online 24/7 and can help you in a few minutes.
 

3. Incorrect service configuration

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

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

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

Some configuration issues that we’ve seen are:

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

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

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

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

WARNING: [mysite.com] server reached max_children setting (30), consider raising it
ERROR: unable to read what child say: Bad file descriptor (9)

If you are not familiar with PHP or web server settings, it is best to ask a server administrator.

If you need help fixing a similar error, click here to talk to our Nginx admins. We are online 24/7 and can attend your ticket within a few mins.

How Bobcares prevents configuration errors

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

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

That is why Dedicated Server Admins audit our customer servers at least once a month.

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

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

4. Service port blocked in firewall

Firewalls are the bedrock of server security. But if not setup right, these firewalls can cause legitimate requests to be blocked or services to fail.

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

But firewalls by default block uncommon ports such as 7080, and it will result in Nginx unable to connect to Apache.

Result? 502 Bad Gateway error.

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

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

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

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

5. Web application bugs

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

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

[notice] child pid 27831 exit signal Segmentation fault (11)

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

If you’re facing this issue right now, our Nginx experts can help you in a few minutes. Click here to open a support request. We are online 24/7.

In Summary

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

  • Nfs rivals ошибка 0xc000007b
  • Nfs pro street исправление ошибок
  • Nfs payback ошибка directx error
  • Nfs payback ошибка directx 512mb
  • Nfs no limits ошибка загрузки последнего облачного сохранения