Начинающие веб-мастера и системные администраторы временами сталкиваются с ошибкой 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 ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
While web browsing, you must have noticed websites returning 502 Bad gateway NGINX error. It is really frustrating to keep seeing this error again and again. While sometimes, your website runs well and returns the same error after a couple of hours.
There are a few reasons why you will find this error message. You might see the following error messages due to the customised 502 Bad Gateway error message.
Here is the list of most common 502 error messages:
- “502 Bad Gateway”
- “502 Bad Gateway NGINX”
- 502 bad gateway nginx/1.14.0 (ubuntu
- “502 Service Temporarily Overloaded”
- “502 Proxy Error”
- “Error 502”
- “HTTP Error 502 – Bad Gateway”
- “HTTP 502”
You will find 502 Bad Gateway Error while-
- Nginx running as a proxy for Apache web server.
- Nginx running with PHP5-FPM.
- Nginx running with PHP7-FPM.
- Nginx running with other services as a gateway.
- Bad buffering / timeout configuration.
Such type of error is referred to as an HTTP Status Code Error. It generally occurs at the gateway. Where gateway is an access point, a bridge communicates between the two servers. In this case, the gateway can be a service or application that is working and receiving requests from Nginx web server.
Let’s dive deep into the reasons to understand the 502 Bad Gateway Nginx Error.
1. NGINX as a proxy for Apache
While using NGINX as a proxy for Apache, there might be a possibility that Apache is not well configured and this might result in 502 Bad Gateway Error. In most of the cases, it can be resolved by just restarting the Apache web server.
2. NGINX with PHP5-FPM
While using NGINX with PHP5-FPM, if it is not well configured, the website will throw 502 Bad Gateway Error. There might be a possibility that PHP5-FPM will get overloaded with too many requests, maybe because of PPC running on that website. In this case, restart PHP5-FPM and check the error logs.
3. NGINX with Services/Apps
You should restart the other services that you are using along with the NGINX with some service or Apps and check the error logs.
These 3 reasons will help you understand the reason for the 502 Bad Gateway Error. It is very important that you know what services you are using and whether it is configured correctly or not. To know the issue, you need to check the log files and then you will get some idea and find the right solution.
Here is the simple command for NGINX that you can use to check your logs and identify the issue:
tail -f /var/log/nginx/error.log
Note: Setting up error logs plays a significant role in identifying server errors. You can check the official documentation of NGINX to configure error logging.
Now, Let’s have a look at the other quick solutions for 502 Bad Gateway Nginx Error:
Solutions For 502 Bad Gateway Nginx Error
Solution 1: Increase Buffer & Timeout Inside http{..}
Block
You need to increase buffer and timeout inside nginx.conf
file under http{..}
block section. Run the following command and edit the nginx.conf
.
sudo vim /etc/nginx/nginx.conf
Add the following under http{..}
block:
http { #... fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; #... }
Solution 2: Ensuring PHP-FPM5 is Listening Properly
Ensure that your PHP5-FPM is listening according to what you have configured in NGINX. Open the www.conf
file and search for one of these two options:
listen = /var/run/php5-fpm.sock
or
listen = 127.0.0.1:9000
In Ubuntu
sudo vim /etc/php5/fpm/pool.d/www.conf
In CentOS
sudo vim /etc/php-fpm.d/www.conf
After ensuring what PHP-FPM listening according to NGINX, restart the PHP-FPM service.
You can use one of the following commands to restart PHP-FPM:
Using SysV Init scripts directly:
/etc/init.d/php-fpm restart # typical /etc/init.d/php5-fpm restart # debian-style
Using a service wrapper script
service php-fpm restart # typical service php5-fpm restart # debian-style
Using Upstart (e.g. Ubuntu)
restart php5-fpm # typical (ubuntu is debian-based) restart php-fpm # uncommon
Using systemd
(newer servers)
systemctl restart php-fpm.service # typical systemctl restart php5-fpm.service # uncommon
If you are getting confused by seeing this list of commands. I personally advise you to use to get your work done:
sudo service php5-fpm restart
Solution 3: Disable APC Cache
Disable APC Cache if used, instead, try Xcache, APC can cause this kind of errors under particular environments causing segmentation faults.
Solution 4
Once you check the log file, you will find error stating some like this:
php5-fpm.sock failed (13: Permission denied) error.
Most of the people get this error because of the PHP update. PHP fixed a security bug where o had rw
permission to the socket file.
To get rid of this error:
Open /etc/php5/fpm/pool.d/www.conf
Uncomment all permission lines, like:
listen.owner = www-data listen.group = www-datalisten.mode = 0660
And finally, restart the PHP-FPM using the command:
sudo service php5-fpm restart
Note: If your web server is running as a user other than www-data, you will require updating the www.conf file accordingly.
Other Error Fixes
- Error Establishing a Database Connection in WordPress Fix
- PHP5-FPM 502 Bad Gateway Error (connect() to unix:/var/run/php5-fpm.sock failed (2: No such file or directory)
- Your PHP installation appears to be missing the MySQL extension which is required by WordPress
- 5 Simple Steps to Fix 504 Gateway Timeout Nginx Error
If you have any other way to fix this issue, please share them with us in the comment section below or contact me on my email [email protected].
Опубликовано: вторник, 4 апреля 2023 г. в 20:32
- DevOps
502 Bad Gateway обычно возникает, когда Nginx работает, как обратный прокси-сервер и не может подключиться к серверным службам. Это может быть связано со сбоем службы, сетевыми ошибками, проблемами конфигурации и т.д. Рассмотрим пять основных причин возникновения этой ошибки и то, как их исправить.
Поддерживать сервер сложно.
Вам приходится иметь дело со всеми обновлениями, исправлениями безопасности и случайными ошибками сервера (они же ошибки из ада).
Одной из таких распространённых ошибок на серверах Nginx является 502 Bad Gateway
.
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.