502 bad gateway nginx error

502 bad gateway nginx error

A Bad Gateway Error is a general indicator that there's something wrong with a website's server communication. Since it's just a generic. sprers.eu › tutorials › bad-gateway. “Error – Bad Gateway” typically comes either from your server itself or a proxy that might be sitting in front of the server. Wordfence should not produce.

502 bad gateway nginx error - does

Why Am I Seeing NGINX Bad Gateway: PHP-FPM?

Introduction

Error Bad Gateway is common among website users. There are various possible reasons for this error and different ways to solve it. In this article, we will look at the main possible causes and how they can be solved by users and web developers.

                 

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

      

What does NGINX Bad Gateway mean?

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

          

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

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

             

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

                            

What is PHP-FPM used for?

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

                  

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

                                 

                                                     

Possible reasons for Bad Gateway

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

           

NGINX is not running

If you see error , then first you need to check if NGINX is running. To do this, run the following command:

        

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

         

PHP-FPM is not running

The next reason for the error is PHP-FPM not running. If you are on Linux, you can check if PHP-FPM is running using the following command:

     

If no PHP-FPM processes are displayed as a result of this command, then you need to run PHP-FPM to resolve error

     

PHP-FPM timeout expires

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

                         

Firewall blocks requests

A firewall can block communication between the edge servers and the origin server. Some DDoS protection systems or security plugins of your CMS can also block requests from servers.

           

A domain name is not allowed

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

           

Server is unavailable

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

             

How to solve error?

Most often, the error occurs due to problems on the side of the website. However, there are times when the cause is in the user’s device. You can check if only you have connection problems or other people also cannot establish a connection to this website. To do this, use one of the tools that check the status of the site and whether it is working or not. For example use one of the following tools or other similar ones: sprers.eu, sprers.eu To learn more about the cause of error , you can examine the NGINX log file in your computer (/var/log/nginx/sprers.eu).

                      

As visitor

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

  1. Reload the page in the browser. Often the error is temporary and a simple reboot can help.
  2. Clear browser cache and delete cookies. The browser can save old or corrupted files and data that can cause the error.
  3. Try using a different browser. There may be a problem in the specific browser you are using, and the error will not occur in another browser.
  4. Restart your computer and network equipment. Perhaps this is the problem and after a reboot, the error will disappear.
  5. Check plugins and extensions in your browser. If you use any plugins or extensions and the website works in another browser, then it is possible that they are blocking the connection. Disable all installed plugins and extensions and check the connection again.
  6. Change your DNS server. Changing the DNS server may resolve the error. You can choose Open DNS or Google DNS servers.

                

As developer

In most cases, error occurs for all users due to the fact that the problem is on the website. As a web developer, you can do the following:

  1. Check if your server is available.
  2. Check the firewall logs for unusual crashes.
  3. If you are using Cloudflare, then it returns a Bad Gateway error to your visitors when a certain limit is reached. Try to disable Cloudflare.

                 

Monitoring your system metrics with Hosted Graphite by MetricFire

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

                      

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

  1. Dashboard templates. You can design your dashboard in templates as if you were writing code.  With templates, you can use the same design in different environments.
  2. Annotations. You can create logs and comments on your chart manually or automatically.
  3. Custom Plugins. Grafana has the ability to install external plug-ins that allow you to expand its basic functionality.
  4. SQL support. With SQL support, you can easily pull data from a variety of data sources.
  5. Alerts. Grafana can send users notifications about important incidents.

                         

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

                

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

                 

To learn more about how to integrate Graphite and Grafana with your system, book a demo with our team or sign up for the MetricFire free trial today.

                                     

Conclusion

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

          

Book a demo with MetricFire experts or sign up for the free trial today and learn more about our features.

#nginx

NGINX Bad Gateway: Gunicorn

tutorial / infrastructure monitoring / log management / nginx / troubleshooting / web server

Editor’s note: Gunicorn 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 Bad Gateway errors. If you’re not using Gunicorn, check out our other article on troubleshooting NGINX s with PHP-FPM as a backend.

Gunicorn is a popular application server for Python applications. It uses the Web Server Gateway Interface (WSGI), which defines how a web server communicates with and makes requests to a Python application. In production, Gunicorn is often deployed behind an NGINX web server. NGINX proxies web requests and passes them on to Gunicorn worker processes that execute the application.

NGINX will return a Bad Gateway error if it can’t successfully proxy a request to Gunicorn or if Gunicorn fails to respond. In this post, we’ll examine some common causes of errors in the NGINX/Gunicorn stack, and we’ll provide guidance on where you can find information you need to resolve these errors.

Explore the metrics, logs, and traces behind NGINX Bad Gateway errors using Datadog.

Get started

Some possible causes of s

In this section, we’ll describe how the following conditions can cause NGINX to return a error:

If NGINX is unable to communicate with Gunicorn for any of these reasons, it will respond with a error, noting this in its access log (/var/log/nginx/sprers.eu) as shown in this example:

sprers.eu

NGINX’s access log doesn’t explain the cause of a error, but you can consult its error log (/var/log/nginx/sprers.eu) to learn more. For example, here is a corresponding entry in the NGINX error log that shows that the cause of the error is that the socket doesn’t exist, possibly because Gunicorn isn’t running. (In the next section, we’ll look at how to detect and correct this problem.)

sprers.eu

Gunicorn 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 Gunicorn isn’t running, NGINX will return a error for any request meant to reach the Python application. If you’re seeing s, first check to confirm that Gunicorn is running. For example, on a Linux host, you can use a command like this one to look for running Gunicorn processes:

On a host where Gunicorn is serving a Flask app named , the output of the above command would look like this:

If the output of the command doesn’t show any Gunicorn primary or worker processes, see the documentation for guidance on starting your Gunicorn daemon.

In a production environment, you should consider using systemd to run your Python application as a service. This can make your app more reliable and scalable, since the Gunicorn daemon will automatically start serving your Python app when your server starts or when a new instance launches.

Once your Gunicorn project is configured as a service, you can use the following command to ensure that it starts automatically when your host comes up:

Then you can use the command to see information about your service:

On a Linux server that has Gunicorn installed (even if it is not running), the output of this command will be:

To see information about your Gunicorn service, use this command:

This command should return an output of . If it doesn’t, you can start the service with:

If Gunicorn won’t start, it could be due to a typo in your unit file or your configuration file. To find out why your application didn’t start, use the command to see any errors that occurred on startup and use this information as a starting point for your troubleshooting:

NGINX can’t access the socket

When Gunicorn starts, it creates one or more TCP or Unix sockets to communicate with the NGINX web server. Gunicorn uses these sockets to listen for requests from NGINX.

To determine whether a error was caused by a socket misconfiguration, confirm that Gunicorn and NGINX are configured to use the same socket. By default, Gunicorn creates a TCP socket located at You can override this default by using Gunicorn’s switch to designate a different location—a different TCP socket, a Unix socket, or a file descriptor. The command shown here starts Gunicorn on the localhost using port (Flask apps typically run on port , but that’s also the port used by the Datadog Agent by default, so we’ll adjust our examples to avoid any conflict.)

If your Gunicorn project is running as a systemd service, its unit file (e.g., /etc/systemd/system/sprers.eue) will contain an line where you can specify the bind information, similar to the command above. This is shown in the example unit file below:

sprers.eue

Alternatively, your bind value can be in a Gunicorn configuration file. See the Gunicorn documentation for more information.

Next, check your sprers.eu file to ensure that the relevant block specifies the same socket information Gunicorn is using. The example below contains an directive that prompts NGINX to include proxy information in the headers of its requests, and a directive that specifies the same TCP socket named in the Gunicorn options shown above.

sprers.eu

If Gunicorn is listening on a Unix socket, the option will have a value in the form of /path/to/sprers.eu, as shown below:

sprers.eu

Just as with a TCP socket, you can prevent errors by confirming that the path to this socket matches the one specified in the NGINX configuration.

Unix sockets are subject to Unix file system permissions. If you’re using a Unix socket, make sure its permissions allow read and write access by the group running NGINX. (You can use Gunicorn’s flag to designate the socket’s permissions.) If the permissions on the socket are incorrect, NGINX will log a error in its access log, and a message like the one shown below in its error log:

sprers.eu

Gunicorn is timing out

If your application is taking too long to respond, your users will experience a timeout error. Gunicorn’s timeout defaults to 30 seconds, and you can override this in the configuration file, on the command line, or in the systemd unit file. If Gunicorn’s timeout is less than NGINX’s timeout (which defaults to 60 seconds), NGINX will respond with a error. The NGINX error log shown below indicates that the upstream process—which is Gunicorn—closed the connection before sending a valid response. In other words, this is the error log we see when Gunicorn times out:

sprers.eu

Your Gunicorn log may also have a corresponding entry. (Gunicorn logs to by default; see the documentation for information on configuring Gunicorn to log to a file.) The log line below is an example from a Gunicorn log, indicating that the application took too long to respond, and Gunicorn killed the worker thread:

You can increase Gunicorn’s timeout value by adding the flag to the Gunicorn command you use to start your application—whether it’s in an directive in your unit file, in a startup script, or using the command line as shown below:

Raising Gunicorn’s timeout could cause another issue: NGINX may time out before receiving a response from Gunicorn. The default NGINX timeout is 60 seconds; if you’ve raised your Gunicorn timeout above 60 seconds, NGINX will return a Gateway Timeout error if Gunicorn 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 item to the block in /etc/nginx/sprers.eu:

sprers.eu

Reload your NGINX configuration to apply this change:

Next, to determine why Gunicorn 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 errors, you can collect your logs with a log management service. NGINX logging is active by default, and you can customize the location, format, and logging level.

By default, Gunicorn logs informational messages about server activity, including startup, shutdown, and the status of Gunicorn’s worker processes. You can add custom logging to your Python application code to collect logs corresponding to any notable events you want to track. This way, when you see a error in NGINX’s access log, you can also reference the NGINX error log and your Python application logs. You can get even greater visibility by collecting logs from relevant technologies like caching servers and databases to correlate with any NGINX error logs. Aggregating these logs in a single platform gives you visibility into your entire web stack, shortening your time spent troubleshooting and reducing your MTTR.

Collect APM data from your web stack

APM can help you identify bottlenecks and resolve issues—like errors—that affect the performance of your app. The screenshot below shows a flame graph—a timeline of calls to all the services required to fulfill a request. Service calls are shown as horizontal spans, which illustrate the sequence of calls and the duration of each one.

Additionally, APM visualizations in Datadog show you your app’s error rates, request volume, and latency, giving you valuable context as you investigate performance problems like errors.

Datadog’s Python tracing supports numerous Python frameworks, so it’s easy to start tracing your applications without making any changes to your code. See the Datadog docs for information on collecting APM data from your Python applications.

OK

The faster you can diagnose and resolve your application’s 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, Gunicorn, and more than other technologies. If you don’t yet have a Datadog account, sign up for a day free trial and get started in minutes.


Want to work with us? We're hiring!

Nginx was launched in as an open-source web server. Since the time it has been released, it is very commonly used for hosting websites. Apart from this, it is also being used as Load Balancer, Email Proxy, Reverse Proxy, and HTTP Cache. Like every other web server, Nginx is also prone to certain errors, out of which the most common one is the Bad Gateway error. This is a highly generic type of error that arises when you try to access a web server but fail to reach it. In that case, your browser may render the Bad Gateway error. Since there is no other information that appears along with this error, it leaves the user clueless about what exactly went wrong and how they can fix it.

Therefore, in today’s article, we will try to look for all the potential causes of the Bad Gateway error in Nginx, as well as the ways on how we can possibly fix it.

Causes of Bad Gateway Error in Nginx

There could be multiple reasons for a Bad Gateway error in Nginx, and the most common ones are listed below:

Unreachable Domain
Whenever you type in a domain name in the search bar of your browser and press the Enter key to access that website, the very first task that is performed is contacting your Domain Name System (DNS). The DNS server maps the specified domain name onto its reserved IP address and then contacts the respective server, which in turn responds to you by displaying the requested web page on your web browser. However, at times, the DNS server fails to reach the specified domain because of a Bad Gateway error in Nginx. This may happen because of certain changes taking place in your DNS, which takes a sufficient amount of time to take effect after it starts working correctly.

Overly Activated Firewalls
At times, your Firewall settings are so strict and hard that they even block legitimate users and disallow them to reach your site. This, in turn, may cause the users to see a Bad Gateway error whenever they try to access your website.

Hosting Server Goes Down
Since the servers have a finite capacity in which they cannot entertain user requests, therefore, once that capacity is reached, all the future incoming users might experience a Bad Gateway error since your server will be down. Another reason for it could be that you have intentionally brought down your server for maintenance.

Fixing the Bad Gateway Error in Nginx

Depending on the causes of the Bad Gateway error in Nginx, you can try to resolve it by using any of the following solutions:

Refresh your Web Page
At times, you can see a Bad Gateway error only because of some temporary connectivity issues, which can be resolved simply by refreshing your web page and checking if you can access the web page or not. If you still fail to reach the desired web page, then you might also try to clear your browser cache because sometimes, a Bad Gateway error response is saved in your browser cache. Due to this, your browser renders this error again and again, so clearing the cache might resolve this issue.

Perform a Ping Test
If you are still not able to access your web server even after refreshing the web page and clearing the browser cache, then your web server might have some serious connectivity issues. In that case, you can try to perform a Ping Test where you send the Ping request to your server and check if it is reachable or not. If your server is reachable, then you will be able to access it, if not, then you will have to look for the other solutions that are listed below.

Look for Potential Changes in your DNS
You might have changed your hosting service provider or changed the IP address with whom one can contact your web server. These changes are always reflected in the DNS server, but they take some time to take place correctly. In that case, you need to wait till the changes have taken effect all across your DNS, after which you will no longer be seeing the Bad Gateway error in Nginx.

Monitor your Server Logs
Server logs contain detailed information about the status of your server and all the activities it performs. If you are monitoring the server logs regularly, then they can help you a lot in figuring out exactly what went wrong, hence enables you to fix the Bad Gateway error in Nginx since knowing the exact cause of the error, is in fact, the first step towards resolving that error.

Recheck your Firewall Configurations
You need to apply this fix if you have figured out your Firewall configurations to be too strict that they are even blocking legitimate users to access your website. In that case, resetting your Firewall configurations can easily fix the Bad Gateway error in Nginx.

Debug your Website’s Code
At times, the problem does not trace back to the connectivity issues, rather, it is your website’s code that is faulty, which causes the Bad Gateway error in Nginx. Manually figuring out such errors is nearly impossible, which is why it is highly recommended for you to debug your website&#;s code in a sandboxed environment. Doing this will not only pinpoint the exact issue that you can immediately fix but will also prevent your physical system from getting harmed by running a faulty code on it since you are running it in a sandboxed environment.

Try Contacting your Hosting Service Provider
Sometimes when you cannot host your own web server, you take the hosting services on rent from a hosting service provider. In that case, the problem that is causing the Bad Gateway error in Nginx, possibly, does not reside in your end, rather, there is some issue with the hosting service that you are getting. The only solution to this problem is contacting your hosting service provider, who will not only take the responsibility of figuring out that issue but might also suggest ways in which you can prevent this error from recurring in the future.

Conclusion

In this article, we provided you a brief introduction of Nginx and the most common type of error that this webserver faces, specifically, the Bad Gateway error. Then, we also stated all the possible causes behind this error. Finally, we shared with you all the different solutions on how you can resolve this error in Nginx.

When NGINX proxy server receives a bad response, then it returns Bad Gateway error to client browser. Here&#;s how to fix Bad Gateway error in NGINX.

 

What is a Bad Gateway Error in Apache

You get Bad Gateway Error in NGINX when it is acting as a reverse proxy and receives a bad response from one of the original back end servers. So NGINX returns Bad Gateway error to client browser. There are various reasons why NGINX gives Bad Gateway response that we will look at further. Sometimes, it may even be due to a temporary network issue that gets fixed automatically.

Bonus Read : How to Increase Request Timeout in NGINX

 

What Causes Bad Gateway Error

Here are the different reasons why you get Bad Gateway Error:

1. Server is down

If your back end server (not reverse proxy server) is overloaded with too many requests and goes down then NGINX will return Bad gateway error. It can also happen if your server goes down due to faulty code, plugins and modules.

2. Server restarts frequently

If your back end server is not configured properly, then it might restart repeatedly and cause NGINX to give Bad Gateway response.

3. Network Issues

This can also happen due to network issues such as DNS resolution issues, routing problems, or firewall blocking server.

Bonus Read : How to Increase File Upload Size in NGINX

 

How to Fix Bad Gateway Error in NGINX

There are several ways to fix Bad Gateway error in NGINX, both as web developer as well as website visitor. We will look at both cases one by one.

Here&#;s what you can do to fix Bad Gateway Error in NGINX, if you are a website administrator or web developer:

  1. Use DNS testing tools to ensure that your domain name resolves correctly.
  2. Use site ping tools to check if your site is up and running for others. Sometimes, it may be down just for you, due to ISP or network issues.
  3. Monitor server load to ensure that it is not overloaded
  4. Inspect firewall logs to determine if there is a sudden increase in blocked requests
  5. Update plugins and modules to the latest versions
  6. Use network monitoring issues to identify network issues
  7. Identify and optimize slow running queries

 

Bonus Read : How to Hide NGINX Server Version from Header

 

Here&#;s what you can do to fix Bad Gateway Error in NGINX, if you are a website visitor:

  1. Clear browser cache and reload web page.
  2. Use ping tools to check if your site is up and running for others.
  3. Disable browser plugins & extensions and try accessing the website
  4. Check if your ISP is blocking the website.

 

Hopefully, the above tips will help you fix Bad Gateway Error in NGINX web server.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!

mm

About Ubiq

Ubiq is a powerful dashboard & reporting platform for small & medium businesses. Build dashboards, charts & reports for your business in minutes. Get insights from data quickly. Try it for free today!

Nginx bad gateway. permalink.

Fix Bad Gateway Error

So, you are at your work desk ready to work hard and conquer the day. But wait! As you open the website needed for your tasks, this happens –

 Bad Gateway Error

Frustrating isn’t it? You don’t understand what has happened or why! But you know you have to get it fixed as soon as possible.

Let us take a closer look at this issue.

What is Bad Gateway Error?

To put it simply, a Bad Gateway error indicates that there is something very wrong in the server communication of the website you are trying to access. When this happens, the error web page is displayed to the visitors, as shown earlier in the picture above.

In technical terms, a Bad Gateway error means that the edge server (acting as proxy or gateway server) has received an invalid response from the origin server (upstream server). In the followings sections, we will discuss why this error usually pops up.

Different forms of the Bad Gateway Error

Due to the technical differences of the browsers, operating systems and web servers, the Bad Gateway error can project itself in different ways. But fortunately (or unfortunately), they mean the same thing.

Below is a list that tells you about the most common variations of this irritating issue –

  • “ Bad Gateway”
  • “Error ”
  • A blank white screen
  • “ Server Error: The server encountered a temporary error and could not complete your request”
  • “HTTP ”
  • “HTTP Error – Bad Gateway”
  • “ Proxy Error”
  • “ Service Temporarily Overloaded”
  • bad gateway Cloudflare
  • That’s an error
  • Bad Gateway: The proxy server received an invalid response from an upstream server
  • Temporary Error ()

Why does NGINX return the Bad Gateway error?

The PHP-FastCGI Process Manager (PHP-FPM) is used for working on server requests in PHP apps. This is usually run behind an NGINX web server. The server throws a Bad Gateway error if PHP-FPM does not respond to its server request, or NGINX is not able to proxy a request properly.

Let us check out some other causes why this may happen –

  • PHP-FPM is not running
  • NGINX is not able to communicate with PHP-FPM
  • PHP-FPM timeout

PHP-FPM is not running

NGINX might throw the error if a request sent to the PHP application does not reach it. This happens when the PHP-FPM is not running. In that case, you need to check whether the PHP-FPM is running properly. If you are on a LINUX host, use the pscommand to verify whether the PHP-FPM processes that are currently running, like this –

To fix this situation, you have to perform the following steps –

  • At first, check the error logs
  • Then, run the command given below on a LINUX terminal
  • The output of the command will be something like this –

In the code written above, you can see the line

“65 connect() to unix:/opt/bitnami/php/var/run/sprers.eu failed”

This line explains that the NGINX server was not able to connect to the PHP-FPM server.

To fix this, just restart the PHP-FPM service by running the command below –

sudo service php-fpm start

If you are developing an application, you must use the systemd to execute the PHP-FPM as a service. The systemd is a useful suite of system components for LINUX systems. Using this will make your PHP application much more scalable and reliable. This is because the PHP-FPM daemon will communicate with the app when you start the server, or if a new instance is launched.

While setting up or configuring PHP, you can add the PHP-FPM as a systemd service. After it is configured as a service, use the command given below to make sure that it initiates when you start the server.

To check the status of the PHP-FPM service, run this command –

Output

Or

Output:

This indicates that the PHP-FPM service not running. Thus, you need to start the php-fpm service. Use the command below –

This will fix the error.  

NGINX is Not Able to Communicate with PHP-FPM

After PHP-FPM is initiated, TCP or UNIX sockets are created to interact with the NGINX server. But if you are encountering a error, it might be due to incorrect NGINX & PHP-FPM configuration settings. Both of them must be configured to make use of the same socket.

In this situation, you can check the error logs using the command given below –

2: No such file or directory

This line indicates that the configuration settings are not correct.

PHP-FPM Configuration

PHP-FPM is often configured and optimized when you are planning to scale beyond a single system. Developers usually configure PHP-FPM for maximum performance and so that they can cut down on their server bills too!

PHP configuration file

You have to remember that these permissions must allow the user and group running the NGINX server accessibility to the socket. If you mess up the permissions while configuring the file, NGINX will throw a error. This error will be logged into the access log and a message will be shown, like this –    

To determine whether a error was caused by a socket misconfiguration, confirm that PHP-FPM and NGINX are configured to use the same socket.

Look for this line of code –

Inside the sprers.eu file, make sure that the location block specifies the same socket. You can see in the code given below, that the include directive loads some of the basic information for PHP-FPM. The fastcgi_pass directive mentions the UNIX socket present in the main configuration file.      

In the above code, we need to check whether the “fastcgi_pass” and listen variable are the same.

PHP-FPM timeout

Users often experience a PHP-FPM timeout error if their application is taking too much time to respond. In the pool configuration’s request_terminate_timeout directive, the default timeout limit is 20 seconds. The timeout for NGINX is 60 seconds. The timeout error is shown when the PHP-FPM timeout is less than the NGINX timeout.

This is the error log you will see when the timeout occurs –

Output:

By configuring the PHP-FPM timeout setting, you may prevent this issue. But it may cause another problem. As the default timeout for NGINX is 60 seconds, if the PHP-FPM timeout is raised above this limit - it can result in Gateway Error. This can be stopped by raising the timeout value to 90 seconds as we have done here –

You can then restart PHP-FPM by typing the following code –

You can also reload NGINX to make the changes applicable by using this code –

PHP-FPM Server Reached Max Children Settings

The error is often encountered when the application server takes too long to respond to a request. This may be due to the following reasons –

  • Many concurrent visitors on the site increasing the site’s traffic way too much
  • Poor code and buggy scripts leading to slow execution of the PHP program
  • The setting of max_children is very low inside the config file

To prevent these errors, you have to analyze the server’s resource usage and performance.  

You need to check which resource is taking longer to respond. Additionally, you can increase the number of process in sprers.eu file.

How to Handle This Error?

You can check out this error by accessing the php-fpm error log –

For this, you need to check php-fpm logs. You can use this command –   

Output:

To fix this error, you can increase the number of processes. Use the code below –

Default Settings

Updated Value

Conclusion

Now you have an idea of how to handle the Bad Gateway error. Apart from the solutions mentioned above, you must also try changing your browser. You can clear out cookies and cache files. If you are using too many extensions and plugins in your web browser, try disabling them to solve the Bad Gateway issue.  


NGINX Bad Gateway: PHP-FPM

tutorial / log management / infrastructure monitoring / nginx / troubleshooting / web server

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 Bad Gateway errors. If you’re not using PHP-FPM, check out our other article on troubleshooting NGINX s 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 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 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 Bad Gateway errors using Datadog.

Try it free

Some possible causes of s

In this section, we’ll describe how the following conditions can cause NGINX to return a error:

If NGINX is unable to communicate with PHP-FPM for any of these reasons, it will respond with a error, noting this in its access log (/var/log/nginx/sprers.eu) as shown in this example:

sprers.eu

NGINX’s access log doesn’t explain the cause of a error, but you can consult its error log (/var/log/nginx/sprers.eu) to learn more. For example, here is a corresponding entry in the NGINX error log that shows that the cause of the 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.)

sprers.eu

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 error for any request meant to reach the PHP application. If you’re seeing s, first check to confirm that PHP-FPM is running. For example, on a Linux host, you can use a 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 ):

If the output of the command doesn’t show any PHP-FPM primary or pool processes, you’ll need to get PHP-FPM running to resolve the 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:

Then you can use the command to see information about your service:

On a PHP server that has PHP-FPM installed (even if it is not running), the output of this command will be:

To see information about your PHP-FPM service, use this command:

This command should return an output of . If it doesn’t, you can start the service with:

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 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//fpm/pool.d/. Each pool’s socket is defined in a directive in the pool’s configuration file. For example, the directive below configures a pool named to use a Unix socket located at /run/php/sprers.eu:

sprers.eu

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 worker pool, NGINX would return a and its error log entry would include:

sprers.eu

Check your sprers.eu file to ensure that the relevant block specifies the same socket. The example below contains an directive that loads some general configuration information for PHP-FPM, and a directive that specifies the same Unix socket named in the sprers.eu file, above.

sprers.eu

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:

sprers.eu

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 error in its access log, and a message like the one shown below in its error log:

sprers.eu

Note that the default values of and match the default owner and group running NGINX, and defaults to Using these defaults, NGINX should be able to access the socket.

If PHP-FPM is listening on a TCP socket, the pool conifguration’s directive will have a value in the form of , as shown below:

sprers.eu

Just as with a Unix socket, you can prevent 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 directive (and defaults to 20 seconds)—is less than NGINX’s timeout (which defaults to 60 seconds), NGINX will respond with a 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:

sprers.eu

In this case, the PHP-FPM log (which by default is located at /var/log/sprers.eu) shows a correlated message which provides further information:

sprers.eu

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 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 item to the block of /etc/nginx/sprers.eu:

sprers.eu

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 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 errors.

OK

The faster you can diagnose and resolve your application’s 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 other technologies. If you don’t yet have a Datadog account, sign up for a day free trial and get started in minutes.


Want to work with us? We're hiring!

502 bad gateway nginx error

Share your: 502 bad gateway nginx error

RX CRC ERRORS COUNTER EXPIRED
FATAL ERROR CALL TO UNDEFINED FUNCTION GEOIP_RECORD_BY_ADDR
502 bad gateway nginx error
ERROR DETECTIED IMP297

You can watch a thematic video

#2Ways To Solve 502 Bad Gateway Issues : 2022

0 Comments

Leave a Comment