Configuration
- Ubuntu Server 11.10 64 bit
- Amazon AWS, Ec2, hosted on the cloud
- t1.micro instance
Before I write anything else, I’d like to state that I’ve checked both nginx 502 bad gateway and Nginx + PHP-FPM 502 Bad Gateway threads, which unfortunately haven’t helped me in this regard.
The issue appears to be rather common: a misconfiguration of nginx or php-fpm can lead to a 502 Bad Gateway
error, which is something that I haven’t been able to get rid of. Note that this appears even when I go to my domain root, without specifying any particular directory.
I’m running an Amazon EC2 webserver, with port 9000 enabled, port 80 open, etc.
The question in particular is, how can I get rid of this nasty error? Or, better yet, how can I get php5-fpm
to actually work.
What I Have Attempted so Far
Mostly consistent editing of configuration files, notably php-fpm.conf
and nginx.conf
.
i. php-fpm.conf
I’ve added the following, which hasn’t quite helped much:
;;;;;;;;;;;;;
; Fpm Start ;
;;;;;;;;;;;;;
;pm.start_servers = 20
;pm.min_spare_servers = 5
;pm.max_spare_servers = 35
Now, afterward I tried including my configuration files:
include=/etc/php5/fpm/*.conf
Which only screwed me even further.
Full Configuration
;;;;;;;;;;;;;;;;;;;;;
; FPM Configuration ;
;;;;;;;;;;;;;;;;;;;;;
; All relative paths in this configuration file are relative to PHP's install
; prefix (/usr). This prefix can be dynamicaly changed by using the
; '-p' argument from the command line.
; Include one or more files. If glob(3) exists, it is used to include a bunch of
; files from a glob(3) pattern. This directive can be used everywhere in the
; file.
; Relative path can also be used. They will be prefixed by:
; - the global prefix if it's been set (-p arguement)
; - /usr otherwise
;include=/etc/php5/fpm/*.conf
;;;;;;;;;;;;;;;;;;
; Global Options ;
;;;;;;;;;;;;;;;;;;
[global]
; Pid file
; Note: the default prefix is /var
; Default Value: none
pid = /var/run/php5-fpm.pid
; Error log file
; Note: the default prefix is /var
; Default Value: log/php-fpm.log
error_log = /var/log/php5-fpm.log
; Log level
; Possible Values: alert, error, warning, notice, debug
; Default Value: notice
log_level = notice
; If this number of child processes exit with SIGSEGV or SIGBUS within the time
; interval set by emergency_restart_interval then FPM will restart. A value
; of '0' means 'Off'.
; Default Value: 0
;emergency_restart_threshold = 0
; Interval of time used by emergency_restart_interval to determine when
; a graceful restart will be initiated. This can be useful to work around
; accidental corruptions in an accelerator's shared memory.
; Available Units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
emergency_restart_interval = 0
; Time limit for child processes to wait for a reaction on signals from master.
; Available units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;process_control_timeout = 0
; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
; Default Value: yes
daemonize = no
;;;;;;;;;;;;;
; Fpm Start ;
;;;;;;;;;;;;;
;pm.start_servers = 20
;pm.min_spare_servers = 5
;pm.max_spare_servers = 35
;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ;
;;;;;;;;;;;;;;;;;;;;
; Multiple pools of child processes may be started with different listening
; ports and different management options. The name of the pool will be
; used in logs and stats. There is no limitation on the number of pools which
; FPM can handle. Your system will tell you anyway :)
; To configure the pools it is recommended to have one .conf file per
; pool in the following directory:
include=/etc/php5/fpm/pool.d/*.conf
ii. nginx.conf
In all honesty this configuration is a smattering of a few websites I’ve visited, but I can tell you that before this 502 Bad Gateway business, the server was running fine (without PHP working. Period.).
The issue primarily lies in the fact that something is terribly, terribly wrong. And now, when I try to do a service php5-fpm restart
, it hangs in what I’m guessing is an infinite loop or something, which I can’t even CTRL—C out of.
Full Configuration
user www-data;
worker_processes 1;
pid /var/run/nginx.pid;
events {
worker_connections 64;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush off;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
server {
listen 80;
server_name ec2-xx-xx-xx-xx.compute-x.amazonaws.com;
location ~ ^(.+.php)(.*)$ {
root /home/wayvac/public;
fastcgi_pass unix:/var/run/php5-fpm.pid;
#fastcgi_pass 127.0.0.1:9000; #Un-comment this and comment "fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;" if you are not using php-fpm.
fastcgi_index index.php;
set $document_root2 $document_root;
if ($document_root2 ~ "^(.*\\).*?[\\|/]../(.*)$") { set $document_root2 $1$2; }
if ($document_root2 ~ "^(.*\\).*?[\\|/]../(.*)$") { set $document_root2 $1$2; }
if ($document_root2 ~ "^(.*\\).*?[\\|/]../(.*)$") { set $document_root2 $1$2; }
if ($document_root2 ~ "^(.*\\).*?[\\|/]../(.*)$") { set $document_root2 $1$2; }
if ($document_root2 ~ "^(.*\\).*?[\\|/]../(.*)$") { set $document_root2 $1$2; }
fastcgi_split_path_info ^(.+.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root2$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root2$fastcgi_path_info;
include fastcgi_params;
fastcgi_param DOCUMENT_ROOT $document_root2;
}
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location / {
root /home/wayvac/public;
index index.html index.htm index.php;
}
location ~* .(?:ico|css|js|gif|jpe?g|png)$ {
# Some basic cache-control for static files to be sent to the browser
expires max;
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}
#include drop.conf;
#include php.conf;
}
}
Nginx is one of the fast performing web servers on the internet. Nginx and php-fpm are the most used combinations on the internet to server PHP websites. Sometimes we came across a very bad Nginx 502 Bad Gateway error generated by Nginx server and it is not very easy to identify the problem and fix. Here are some quick solutions to fix Nginx 502 Bad Gateway error on a web-server.
Contents
- 1 How Nginx 502 Bad Gateway Error happens and what is its connection with php-fpm
- 1.1 Nginx 502 Bad Gateway Error with PHP-FPM
- 1.2 Php-fpm is not communicating with Nginx and causing a 502 Bad Gateway Error
- 1.3 502 Bad Gateway Error due to Nginx is timing out
- 1.4 502 Bad Gateway Error due to PHP-FPM is timing out
- 2 Nginx 502 Bad Gateway Error when Nginx as Proxy for Apache
- 3 Nginx with other services/apps and 502 Bad Gateway Error
How Nginx 502 Bad Gateway Error happens and what is its connection with php-fpm
Common 502 errors include the following messages from Nginx server
- “502 Bad Gateway”
- “502 Bad Gateway NGINX”
- “502 Proxy Error”
- “502 Service Temporarily Overloaded”
- “Error 502”
- “HTTP Error 502 – Bad Gateway”
- “HTTP 502 Bad Gateway”
These errors point to the same situation of Nginx server and the error came across below situations
- Nginx server running with php-fpm service
- Nginx is running as a reverse proxy to Apache server
- Nginx running as a gateway to other services like Python, Ruby, etc.
- Bad configuration of cache or timeout.
Now the error says there is a “BAD GATEWAY”. That means Nginx server is trying to communicate to another service through a gateway and it is not getting any answer from that gateway. This is Nginx 502 Bad Gateway error situation.
So Nginx and another service (Apache, php-fpm, other services) running. Both are communicating through a gateway and Nginx is not getting any answer from the gateway. To solve 502 Bad Gateway Error the other service running with Nginx must answer through the gateway.
Usually, this happens due to a misconfiguration in the configuration files of the server. Or the other service is not running properly with Nginx. So to solve this problem a two-step check is required.
- Step 1: Check the other server status, whether it is running perfectly, is it giving the desired output?
- Step 2: Is the configuration correct? Is the second service configured to answer the gateway perfectly?
Nginx 502 Bad Gateway Error with PHP-FPM
The problem occurs due to the following conditions
- PHP-FPM won’t get started
- PHP-FPM not running
- NGINX can’t communicate with PHP-FPM server
- NGINX is timing out
- PHP-FPM is timing out with requests
Check whether php-fpm is running or not
service php-fpm status
or
systemctl status php-fpm.service
will tell you about the current situation of php-fpm server
Just restart the php-fpm server to solve this problem
service php-fpm restart
or
systemctl restart php-fpm.service
for php5 the name of service may be php5-fpm, for PHP 7 it may be php7.0-fpm or php7.1-fpm or php7.2-fpm check accordingly.
Php-fpm is not communicating with Nginx and causing a 502 Bad Gateway Error
This is caused due to the misconfiguration of the php-fpm server or the misconfiguration of Nginx server.
Check the following configuration files in the worker pool configuration (the file is in /etc/php/fpm/pool.d/www.conf
, this may vary with installation) and verify these lines ( www-data is the owner of the web server process, that is nginx)
user = www-data
group = www-data
listen = /var/run/php7-fpm.sock
listen.owner = www-data
listen.group = www-data
then restart the php-fpm service.
If the Nginx server and php-fpm are running and still getting a 502 Bad Gateway error then it is the problem with communicating the gateway. The problem is happening due to the misconfiguration in the file /etc/nginx/sites-enabled/default
, by default or the file name in the name of the website called /etc/nginx/sites-enabled/mywebsite.com.conf
Look at the segment where the fastcgi_pass configuration. It must be the same as the listen in the above configuration
location ~ .php$ {
try_files $uri =404;
fastcgi_pass unix:/var/run/php7-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_nam$
include fastcgi_params;
}
See
listen = /var/run/php7-fpm.sock
and
fastcgi_pass unix:/var/run/php7-fpm.sock
must be the same.
Then restart both Nginx and php-fpm servers. Now check the website whether it is serving properly.
502 Bad Gateway Error due to Nginx is timing out
if php-fpm is running and serving the requests properly then there will be a chance of Nginx is timing out. That is php-fpm do not respond to NGINX in a timely manner will cause a 502 because NGINX couldn’t wait any longer for a response from php-fpm.
In this case, increasing the maximum execution time of the application and NGINX’s timeout window would be the best solution.
To get this we need two changes:
First, increase the maximum execution time of the php-fpm server. To do this open PHP-FPM’s configuration file
sudo nano /etc/php7/fpm/php.ini
find the following line and increase the number to a higher value. Usually 60 or 120.
max_execution_time = 30
The value depends upon the expected execution time of the application running in the php-fpm server. Add some extra buffer time to get rid of the situation again.
Exceptionally large execution time will affect the server performance and it may lead to a dead server process in the memory.
Second, edit the NGINX config
sudo nano /etc/nginx/nginx.conf
add the following within the HTTP block to increase timeout windows, buffers, and buffer sizes:
http { ... fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; }
Save the changes to the file and exit. Now restart Nginx and php-fpm
service php-fpm restart
or
systemctl restart php-fpm.service and
service nginx restart
systemctl restart nginx.service
502 Bad Gateway Error due to PHP-FPM is timing out
if the php-fpm server is timing out upon execution of an exceptionally long PHP script or the script is blocked by a large MySQL query process then these solutions may not work. In that situation, you could temporarily extend PHP’s execution time limit by invoking the set_time_limit()
function from within the PHP application, but if you are continuously reaching into the execution timeout limit then as a long-term solution like profiling or increasing PHP-FPM’s timeout may be more appropriate to get rid of a 502 error more safely. These things must be done after an extensive research of the execution time of the corresponding PHP function or MySQL query. Take a look at the memory and system load during the execution is a must for a smooth operation of this server.
Nginx 502 Bad Gateway Error when Nginx as Proxy for Apache
In this situation, the gateway service is Apache and the Nginx is a proxy for Apache. If apache server dies or it’s not well configured, it can cause this 502 Bad Gateway error. How to fix the apache error? Most of the times, restarting apache web server will get rid of this, but you must check the log files to know why exactly this was caused.
Nginx with other services/apps and 502 Bad Gateway Error
In this situation, the app is gone not responding. Try restarting the other service behind Nginx server and check the logs created by the application to find the exact reason why a 502 Error happened.
Check the status codes HTTP Status Codes on W3C for more details.
Editor’s note: php-fpm uses the term “master” to describe its primary process. Datadog does not use this term. Within this blog post, we will refer to this as “primary,” except for the sake of clarity in instances where we must reference a specific process name.
This post is part of a series on troubleshooting NGINX 502 Bad Gateway errors. If you’re not using PHP-FPM, check out our other article on troubleshooting NGINX 502s with Gunicorn as a backend.
PHP-FastCGI Process Manager (PHP-FPM) is a daemon for handling web server requests for PHP applications. In production, PHP-FPM is often deployed behind an NGINX web server. NGINX proxies web requests and passes them on to PHP-FPM worker processes that execute the PHP application.
NGINX will return a 502 Bad Gateway error if it can’t successfully proxy a request to PHP-FPM, or if PHP-FPM fails to respond. In this post, we’ll examine some common causes of 502 errors in the NGINX/PHP-FPM stack, and we’ll provide guidance on where you can find information that can help you resolve these errors.
Explore the metrics, logs, and traces behind NGINX 502 Bad Gateway errors using Datadog.
Some possible causes of 502s
In this section, we’ll describe how the following conditions can cause NGINX to return a 502 error:
- PHP-FPM is not running
- NGINX can’t communicate with PHP-FPM
- PHP-FPM is timing out
If NGINX is unable to communicate with PHP-FPM for any of these reasons, it will respond with a 502 error, noting this in its access log (/var/log/nginx/access.log) as shown in this example:
access.log
127.0.0.1 - - [31/Jan/2020:18:30:55 +0000] "GET / HTTP/1.1" 502 182 "-" "curl/7.58.0"
NGINX’s access log doesn’t explain the cause of a 502 error, but you can consult its error log (/var/log/nginx/error.log) to learn more. For example, here is a corresponding entry in the NGINX error log that shows that the cause of the 502 error is that the socket doesn’t exist, possibly because PHP-FPM isn’t running. (In the next section, we’ll look at how to detect and correct this problem.)
error.log
2020/01/31 18:30:55 [crit] 13617#13617: *557 connect() to unix:/run/php/php7.2-fpm.sock failed (2: No such file or directory) while connecting to upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.2-fpm.sock:", host: "localhost"
PHP-FPM isn’t running
Note: This section includes a process name that uses the term “master.” Except when referring to specific processes, this article uses the term “primary” instead.
If PHP-FPM isn’t running, NGINX will return a 502 error for any request meant to reach the PHP application. If you’re seeing 502s, first check to confirm that PHP-FPM is running. For example, on a Linux host, you can use a ps
command like this one to look for running PHP-FPM processes:
PHP-FPM organizes its worker processes in groups called pools. The sample output below shows that the PHP-FPM primary process is running, as are two worker processes in the default pool (named www
):
root 29852 0.0 2.2 435484 22396 ? Ssl 16:27 0:00 php-fpm: master process (/etc/php/7.2/fpm/php-fpm.conf)
www-data 29873 0.0 1.5 438112 15220 ? Sl 16:27 0:00 php-fpm: pool www
www-data 29874 0.0 1.6 438112 16976 ? Sl 16:27 0:00 php-fpm: pool www
If the output of the ps
command doesn’t show any PHP-FPM primary or pool processes, you’ll need to get PHP-FPM running to resolve the 502 errors.
In a production environment, you should consider using systemd to run PHP-FPM as a service. This can make your PHP application more reliable and scalable, since the PHP-FPM daemon will automatically start serving your PHP app when your server starts or when a new instance launches. PHP-FPM is included in the PHP source code, so you can add PHP-FPM as a systemd service when you configure PHP.
Once your PHP-FPM project is configured as a service, you can use the following command to ensure that it starts automatically when your server starts up:
sudo systemctl enable php7.2-fpm.service
Then you can use the list-unit-files
command to see information about your service:
sudo systemctl list-unit-files | grep -E 'php[^fpm]*fpm'
On a PHP 7.2 server that has PHP-FPM installed (even if it is not running), the output of this command will be:
php7.2-fpm.service enabled
To see information about your PHP-FPM service, use this command:
sudo systemctl is-active php7.2-fpm.service
This command should return an output of active
. If it doesn’t, you can start the service with:
sudo service php7.2-fpm start
NGINX can’t access the socket
When PHP-FPM starts, it creates one or more TCP or Unix sockets to communicate with the NGINX web server. PHP-FPM’s worker processes use these sockets to listen for requests from NGINX.
To determine whether a 502 error was caused by a socket misconfiguration, confirm that PHP-FPM and NGINX are configured to use the same socket. PHP-FPM uses a separate configuration file for each worker process pool; these files are located at /etc/php/7.2/fpm/pool.d/. Each pool’s socket is defined in a listen
directive in the pool’s configuration file. For example, the listen
directive below configures a pool named mypool
to use a Unix socket located at /run/php/mypool.sock:
mypool.conf
listen = /run/php/mypool.sock
If NGINX can’t access the socket for a particular pool, you can determine which worker pool is involved in the issue by checking which socket is named in the NGINX error log entry. For example, if PHP-FPM had failed to start the mypool
worker pool, NGINX would return a 502 and its error log entry would include:
error.log
connect() to unix:/run/php/mypool.sock failed (2: No such file or directory)
Check your nginx.conf file to ensure that the relevant location
block specifies the same socket. The example below contains an include
directive that loads some general configuration information for PHP-FPM, and a fastcgi_pass
directive that specifies the same Unix socket named in the mypool.conf file, above.
nginx.conf
location / {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/mypool.sock;
}
Unix sockets are subject to Unix file system permissions. The PHP-FPM pool’s configuration file specifies the mode and ownership of the socket, as shown here:
www.conf
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
Make sure these permissions allow the user and group running NGINX to access the socket. If the permissions on the socket are incorrect, NGINX will log a 502 error in its access log, and a message like the one shown below in its error log:
error.log
2020/02/20 17:12:03 [crit] 3059#3059: *4 connect() to unix:/run/php/mypool.sock failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php/mypool.sock:", host: "localhost"
Note that the default values of listen.owner
and listen.group
match the default owner and group running NGINX, and listen.mode
defaults to 0660. Using these defaults, NGINX should be able to access the socket.
If PHP-FPM is listening on a TCP socket, the pool conifguration’s listen
directive will have a value in the form of address:port
, as shown below:
Just as with a Unix socket, you can prevent 502 errors by confirming that the location of this socket matches the one specified in the NGINX configuration.
PHP-FPM is timing out
If your application is taking too long to respond, your users will experience a timeout error. If PHP-FPM’s timeout—which is set in the pool configuration’s request_terminate_timeout
directive (and defaults to 20 seconds)—is less than NGINX’s timeout (which defaults to 60 seconds), NGINX will respond with a 502 error. The NGINX error log shown below indicates that its upstream process—which is PHP-FPM—closed the connection before sending a valid response. In other words, this is the error log we see when PHP-FPM times out:
error.log
2020/02/20 17:17:12 [error] 3059#3059: *29 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php/mypool.sock:", host: "localhost"
In this case, the PHP-FPM log (which by default is located at /var/log/php7.2-fpm.log) shows a correlated message which provides further information:
php7.2-fpm.log
[20-Feb-2020 17:17:12] WARNING: [pool mypool] child 2120, script '/var/www/html/index.php' (request: "GET /index.php") execution timed out (25.755070 sec), terminating
You can raise PHP-FPM’s timeout setting by editing the pool’s configuration file, but this could cause another issue: NGINX may time out before receiving a response from PHP-FPM. The default NGINX timeout is 60 seconds; if you’ve raised your PHP-FPM timeout above 60 seconds, NGINX will return a 504 Gateway Timeout error if your PHP application hasn’t responded in time. You can prevent this by also raising your NGINX timeout. In the example below, we’ve raised the timeout value to 90 seconds by adding the fastcgi_read_timeout
item to the http
block of /etc/nginx/nginx.conf:
nginx.conf
http {
...
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
fastcgi_connect_timeout 90;
fastcgi_send_timeout 90;
fastcgi_read_timeout 90;
}
Reload your NGINX configuration to apply this change:
Next, to determine why PHP-FPM timed out, you can collect logs and application performance monitoring (APM) data that can reveal causes of latency within and outside your application.
Collect and analyze your logs
To troubleshoot application errors, you can collect your logs and send them to a log management service. In addition to the NGINX logs we examined above, PHP can log errors and other events that might be valuable to you. See our PHP logging guide for more information.
When you bring your PHP and NGINX logs into a log management service, combined with logs from relevant technologies like caching servers and databases, you can analyze logs from throughout your web stack in a single platform.
Collect APM data from your web stack
APM can help you identify bottlenecks and resolve issues, like 502 errors, which affect the performance of your app. The screenshot below shows NGINX’s APM data visualized in Datadog. This view summarizes request volume, error rates, and latency for an NGINX-based service and helps you investigate performance problems like 502 errors.
200 OK
The faster you can diagnose and resolve your application’s 502 errors, the better. Datadog allows you to analyze metrics, traces, logs, and network performance data from across your infrastructure. If you’re already a Datadog customer, you can start monitoring NGINX, PHP-FPM, and more than
600 other technologies. If you don’t yet have a Datadog account, sign up for a 14-day free trial and get started in minutes.
Начинающие веб-мастера и системные администраторы временами сталкиваются с ошибкой 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 что это значит и как исправить эту ошибку. Как видите, может быть достаточно много причин ее возникновения, но решить все достаточно просто если внимательно посмотреть логи и понять в чем там действительно проблема. Надеюсь, информация была полезной для вас.
Статья распространяется под лицензией 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].
В этом руководстве мы покажем вам, как исправить 502 ошибки неверного шлюза на веб-сервере Nginx. Если вы запускаете веб-сервер Nginx, вы, возможно, уже столкнулись с досадной ошибкой 502 плохого шлюза. Это довольно распространенная ошибка, скорее всего, вызванная настройками буфера PHP или FastCGI и тайм-аутов. Из этого туториала Вы узнаете, как исправить плохой шлюз Nginx 502 на веб-сервере Nginx. В этом сообщении показано, как решить эту проблему, а также параметры конфигурации, чтобы предотвратить ее повторное появление при перезагрузке.
В этой статье предполагается, что у вас есть хотя бы базовые знания Linux, вы знаете, как использовать оболочку, и, что наиболее важно, вы размещаете свой сайт на собственном VPS. Установка довольно проста и предполагает, что вы работаете с учетной записью root, в противном случае вам может потребоваться добавить ‘ sudo
‘ к командам для получения привилегий root. Я покажу вам пошаговое решение ошибки 502 неверного шлюза на веб-сервере Nginx.
Исправить ошибку 502 Bad Gateway на Nginx
Шаг 1. Сначала проверьте журнал данных веб-сервера Nginx.
Вы можете более подробно увидеть, что конкретно влечет за собой ошибка, перейдя в файл журнала ошибок вашего веб-сервера. Вся информация об ошибках и диагностическая информация хранится в этом файле, что делает его ценным ресурсом для проверки, когда вам нужны дополнительные сведения о конкретной ошибке. Вы можете найти этот файл в Nginx, перейдя в ./var/log/nginx/error.log
Шаг 2. Решите 502 проблемы со шлюзом.
- Метод 1. Изменения в Nginx Config.
Выполните следующую команду, чтобы отредактировать Nginx conf:
sudo nano /etc/nginx/nginx.conf
http { ... fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; ... }
После этого перезапустите службу Nginx, чтобы вступили в силу:
sudo nginx -t sudo systemctl restart nginx
- Метод 2. Измените PHP-FPM для прослушивания сокета Unix или сокета TCP.
nano /etc/php-fpm.d/www.conf
listen = /var/run/php5-fpm.sock To: listen = 127.0.0.1:9000
После этого перезапустите PHP-FPM, чтобы изменить эффект:
sudo systemctl restart php-fpm
Если вы настраиваете php-fpm для прослушивания сокета Unix, вы также должны проверить, что у файла сокета есть правильный владелец и разрешения.
chmod 0660 /var/run/php5-fpm.sock chown www-data:www-data /var/run/php5-fpm.sock
- Метод 3. Отключить APC.
Кэширование APC может вызвать проблемы 502 Bad Gateway в определенных средах, вызывая ошибки сегментации. Я настоятельно рекомендую использовать Memcache (d), но XCache также является хорошей альтернативой.
Поздравляю! Вы успешно решили 502 проблемы со шлюзом. Благодарим за использование этого руководства для исправления 502 проблем со шлюзом в системе Linux. Для получения дополнительной помощи или полезной информации мы рекомендуем вам посетить официальный сайт Nginx .