Ошибка 504 Gateway Time Out

Ошибка 504 Gateway Time Out Хостинг

The 504 Gateway Timeout error is an HTTP status code that means that one server didn’t receive a timely response from another server that it was accessing while attempting to load the web page or fill another request by the browser.

In other words, 504 errors usually indicate that a different computer, one that the website you’re getting the message on doesn’t control but relies on, isn’t communicating with it quickly enough.

Lifewire / Ashley Nicole DeLeon



Are You the Web Manager? See the Fixing 504 Errors on Your Own Site section further down the page for some things to consider on your end.

Содержание
  1. How You Might See the 504 Error
  2. Causes of 504 Gateway Timeout Errors
  3. How to Fix the 504 Gateway Timeout Error
  4. Fixing 504 Errors on Your Own Site
  5. More Ways You Might See a 504 Error
  6. Errors Like 504 Gateway Timeout
  7. Что значит ошибка 504 и когда она появляется
  8. Как исправить ошибку 504 владельцу сайта
  9. Долго обрабатывается скрипт
  10. Проблемы с CDN
  11. Выросла нагрузка на один из серверов
  12. Проверка службы DNS
  13. Спам, вирусы и DDoS-атаки
  14. Проблемы с плагинами в CMS
  15. Как решить проблему, если вы — пользователь
  16. Заключение
  17. What Is the 504 Gateway Timeout Error?
  18. Variations of the 504 Gateway Timeout Error
  19. What Are the Causes of the 504 Gateway Timeout Error?
  20. SEO Impact of the 504 Gateway Timeout Error
  21. How to Fix the 504 Gateway Timeout Error?
  22. 1. Try Reloading the Webpage
  23. 2. Reboot Your Network Devices
  24. 3. Check Your Proxy Settings
  25. 4. Check for DNS Issues
  26. 5. Disable Your Site’s CDN Temporarily
  27. 504 Gateway Timeout at Cloudflare (Variation 1)
  28. 504 Gateway Timeout at Cloudflare (Variation 2)
  29. 504 Gateway Timeout at Cloudflare Due to Large Uploads
  30. 6. Check Server Issues With Your Host
  31. Slow Server Infrastructure
  32. Needs More PHP Workers
  33. Firewall Issues
  34. Network Connectivity Problems
  35. HTTP Timeouts
  36. 7. Check for Spam, Bots, or DDoS Attacks
  37. 8. Repair Your Corrupted WordPress Database
  38. 9. Check Your Site’s Plugins and Themes
  39. 10. Check Error Logs
  40. 11. Configure Apache or Nginx Settings Properly
  41. For Apache Webservers
  42. For Nginx Webservers
  43. Other HTTP Errors Like 504 Gateway Timeout
  44. Summary

How You Might See the 504 Error

Individual websites are allowed to customize how they show «gateway timeout» errors, but here are the most common ways you’ll see one spelled out:

  • 504 Gateway Timeout
  • HTTP 504
  • 504 ERROR
  • Gateway Timeout (504)
  • HTTP Error 504 — Gateway Timeout
  • Gateway Timeout Error

A 504 Gateway Timeout error shows up inside the internet browser window, just like normal web pages do. There might be a site’s familiar headers and footers and a nice, English message on the page, or it could show up on an all-white page with a big 504 at the top. It’s all the same message, regardless of how the website happens to show it.

Causes of 504 Gateway Timeout Errors

Most of the time, a 504 Gateway Timeout error means that whatever other server is taking so long that it’s «timing out,» is probably down or not working properly.

Since this error is usually a network error between servers on the internet or an issue with an actual server, the problem probably is not with your computer, device, or internet connection.

That said, there are a few things you can try, just in case:

How to Fix the 504 Gateway Timeout Error

  1. Retry the web page by selecting the refresh/reload button, pressing F5, or trying the URL from the address bar again.

    Even though the 504 Gateway Timeout error is reporting an error outside of your control, it might only be temporary.


  2. Restart all of your network devices. Temporary problems with your modem, router, switches, or other networking hardware could be causing the 504 Gateway Timeout issue you’re seeing. Just restarting these devices could help.

    While the order you turn off these devices isn’t important, the order that you turn them back on is. In general, you want to turn devices on from the outside-in. If you’re not sure what that means, check out the link at the beginning of this step for a complete tutorial.

  3. Check the proxy server settings in your browser or application and make sure they’re correct. Incorrect proxy settings can cause 504 errors.

    Windows 10 Proxy Settings.


    Most computers don’t have proxy settings at all, so if yours are empty, just skip this step.

    See Proxy.org for an updated, respected list of proxy servers that you can choose from.

  4. Change your DNS servers, especially if all the devices on your network are getting the same error. It’s possible that the 504 Gateway Timeout error you’re seeing is caused by an issue with the DNS servers you happen to be using.

    Unless you’ve previously changed them, the DNS servers you have configured right now are probably the ones automatically assigned by your ISP. Others are also available to choose from. See our Free & Public DNS Servers list for options.


  5. Most major sites have social networking accounts they use to help support their services and some even have telephone numbers and email addresses.




  6. How to Talk to Tech Support


  7. Come back later. You’ve exhausted all your options at this point and the 504 Gateway Timeout error is either in the hands of the website or your ISP to correct. Check back with the site regularly. No doubt it’ll start working again soon.


Fixing 504 Errors on Your Own Site

Very heavy traffic might result in your server serving a 504 error, even though a 503 would probably be a bit more accurate.

Also, make sure your HTACCESS file is correct, especially if you have just reinstalled WordPress.

Finally, consider contacting your hosting company. It’s possible that the 504 error that your website is returning is due to an issue on their end that they’ll need to resolve.

More Ways You Might See a 504 Error

A Gateway Timeout error, when received in Windows Update, generates a 0x80244023 error code or the message WU_E_PT_HTTP_STATUS_GATEWAY_TIMEOUT.

In Windows-based programs that inherently access the internet, a 504 error might show up in a small dialog box or window with the HTTP_STATUS_GATEWAY_TIMEOUT error and/or with a The request was timed out waiting for a gateway message.

A less common 504 error is Gateway Time-out: The proxy server did not receive a timely response from the upstream server, but the troubleshooting (above) remains the same.

Errors Like 504 Gateway Timeout

A number of error messages are similar to the 504 Gateway Timeout error because they all occur on the server side. A few include the 500 Internal Server Error, the 502 Bad Gateway error, and the 503 Service Unavailable error, among a few others.

There are also HTTP status codes that aren’t server-side, but instead client-side, like the commonly seen 404 Not Found error. Several others exist as well, all of which you can see in our HTTP Status Code Errors page.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Чтобы на веб-странице появился контент, браузер должен получить от сервера, на котором расположен сайт, необходимые данные. Когда на устройстве пользователя, на веб-сервере или на другом промежуточном узле (например, прокси) возникают неполадки, вместо содержимого сайта в браузере появляется страница с ошибкой. Для устранения сбоя, необходимо знать, на чьей стороне он произошел и по какой причине. Понять, что является источником проблемы, помогает цифровой код ошибки. Если он имеет формат 5xx, значит, сбой происходит на стороне сервера. Разбираем в статье ошибку 504 на сайте и способы ее устранения.

Что значит ошибка 504 и когда она появляется

Ошибка 504 Gateway Time Out — это ошибка, возникающая при загрузке сайта, если запрос пользователя передавался на сервер, хранящий данные веб-ресурса, через промежуточный сервер, действующий как шлюз или прокси, и в процессе обработки данного запроса один из серверов не получил ответ от другого в течение максимально допустимого времени ожидания. Обмен данными происходит по HTTP, и если возникает «тайм-аут шлюза», браузер показывает на веб-странице код 504, указывающий на соответствующее состояние протокола.

Изображение от Freepik.

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

Как исправить ошибку 504 владельцу сайта

Чтобы исправить ошибку 504, необходимо установить и устранить причину ее возникновения. Некоторые способы решения проблемы требуют вмешательства администратора сайта.

Долго обрабатывается скрипт

Если скрипт тяжелый, сервер может не успеть полностью его обработать до появления ошибки. Лучшим решением проблемы будет облегчение скрипта или его замена. Когда это невозможно, увеличивают период ожидания сервера. Лимит времени, за которое скрипт должен быть отработан, устанавливается через директиву «max_execution_time» в файле «php.ini». По умолчанию он составляет 30 секунд. Чтобы он стал больше, необходимо открыть файл и подставить в строку «max_execution_time = 30» новую допустимую продолжительность операции. Кроме того, поменять настройки можно в Nginx и Apache.

Нестандартные параметры времени ожидания сервера могут понадобиться, если вы используете Nginx в качестве прокси-сервера для Apache. Изменение времени выполнения скрипта на веб-сервере производится в файле «nginx.conf». Порядок действий:

  1. Подключение к серверу по Secure Shell (протоколу для удаленного управления операционной системой).
  2. Ввод команды «sudo nano/etc/nginx/nginx.conf» для запуска файла.
  3. Редактирование блока server: увеличение времени до наступления тайм-аута с 300 секунд до 600:

  4. Перезагрузка веб-сервера командой «service nginx reload».

Коррекцию файлов «php.ini» и «nginx.conf» лучше проводить совместно. В обоих документах необходимо указать одинаковое время обработки запроса.

При использовании Apache время обработки запроса редактируется через «httpd.conf». Что необходимо сделать:

  1. Открыть файл.
  2. Сохранить корректировки и заново запустить сервер.

Проблемы с CDN

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

Иногда ошибка 504 может возникать при использовании CDN. Если после отключения от системы работоспособность сайта восстановится, сообщите о проблеме разработчикам сервиса.

Выросла нагрузка на один из серверов

К повышенной нагрузке на сервер может привести резкий рост трафика. Наплыв пользователей может быть связан как с намеренными действиями владельца веб-ресурса — с запуском рекламной кампании, так и со случайными событиями — временным увеличением спроса на сезонный товар, продающийся в интернет-магазине. Поскольку количество операций, которое сервер может выполнять одновременно, ограничено его вычислительной мощностью, при избыточной нагрузке хостинг-компьютер перестает отвечать на запросы пользователей. Чтобы он снова мог отдавать данные браузеру, достаточно арендовать компьютер с более мощным железом, например, с виртуального хостинга перейти на VPS. Если планируется проведение маркетинговых мероприятий, лучше заранее арендовать дополнительные вычислительные ресурсы (оперативную память, место на жестком диске и т. д.).

В компании «Интернет Хостинг Центр» клиенты могут арендовать в России с бесплатной защитой от DDoS на всех тарифах. Выделенный IP и техподдержка входят в стоимость.

Проверка службы DNS

Проблемы с DNS могут возникнуть на компьютере пользователя. Для их устранения на ПК вызывается командная строка операционной системы, где вводится специальная команда для очистки DNS-кэша, в Windows — это «ipconfig /flushdns».

Спам, вирусы и DDoS-атаки

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

  • проверить наличие антивируса в административной панели хостинга;
  • включить защиту от DDoS;
  • подключить анти-спам плагины в CMS сайта;
  • проверить лог-файлы на наличие часто повторяющихся IP-адресов;
  • установить SSL/TLS;
  • защитить формы обратной связи с помощью капчи;
  • предотвратить публикацию комментариев со ссылками на вредоносное ПО, подключив модерирование контента и так далее.

Проблемы с плагинами в CMS

Функции на сайте, созданном с помощью CMS, реализуются благодаря плагинам. Не все они работают достаточно быстро, некоторые из них обрабатываются медленно, что приводит к тайм-ауту шлюза. Чтобы проверить, не является ли установленный плагин причиной сбоя, его необходимо отключить, а затем запустить сайт без него. Если веб-ресурс загрузится, значит, нужно выбрать другой функциональный модуль.

Как решить проблему, если вы — пользователь

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

  • обновите страницу, заново указав URL в адресной строке и нажав кнопку ввода (Enter);
  • откройте сайт в другом браузере, если в нем сбой не повторится, обновите браузер с ошибкой до последней версии;
  • запустите веб-ресурс на другом устройстве, чтобы проверить, не связаны ли проблемы с программным обеспечением вашего компьютера;
  • очистите файлы кэша и cookies, чтобы избавиться от ошибок, накопленных браузером за длительное время использования;
  • перезагрузите роутер, чтобы устранить конфликт между обновленным ПО провайдера и вашим устройством;
  • очистите кэш DNS через командную строку ОС.

Заключение

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

504 Gateway Timeout

Ошибка зачастую возникает на серверах с установленным   nginx в качестве фронтенда и Apache в качестве бэкенда. Пользователи сервера чаще всего думают, что суть проблемы заключается в nginx, но на самом деле это не так.

О причинах появления ошибки.

Одной из основных причин является возрастание нагрузки на сайт,  при которой количество запросов к серверу apache возрастает  до критического значения и новые запросы стают в очередь.
 В связи с этим время на поступление к обработке запросов (которые попали в очередь)   больше, чем установлено в конфигурации сервера. Запрос не успевает попасть на  обработку и соединение сбрасывается.

Для решения проблемы:

1. Увеличить ресурс сервера, оперативную память, процессор. В большинстве случаев решает проблему, но часто необходимо предпринимать с решением 3.
2. Увеличить количество одновременных процессов apache и лимит времени в конфигурации nginx. Не рекомендовано предпринимать без 1 и 3 пунктов, возможны еще большие проблемы.
3. Провести оптимизацию работы скриптов. Возможно, как самостоятельное решение.
4. В конфигурации nginx увеличить время ожидания
исполнения скрипта:

proxy_read_timeout 120;
proxy_connect_timeout 120;

Существует еще одна распространенная причина.   Скрипт требует значительно больше времени на его обработку, чем отведено сервером.

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

Для решения проблемы:

Можно увеличить значение PHP max_execution_time  или оптимизировать работу скрипта.

Прошу заметить, что сильное увеличение max_execution_time может привести к возникновению первой причины появления ошибки 504 которая описана выше.

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

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. For many blogs and ecommerce platforms, knowing how to fix server errors like this is crucial to keep their hard-earned visitors from bouncing to competitor sites.

As the 504 Gateway Timeout error doesn’t tell you why it occurred, it’s hard to pinpoint what’s causing the server timeout. This article will help you understand it in detail, learn how to diagnose its cause, and then fix it.

After trying all the various solutions mentioned in the post, your site should be up and running in no time.

Sound interesting? Let’s dive in!

Check Out Our Video Guide To Fixing the 504 Gateway Timeout Error on Your Site

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. 🤔 Learn how to fix it with this guide quickly. ⬇️Click to Tweet

What Is the 504 Gateway Timeout Error?

The 504 Gateway Timeout Error indicates that the server didn’t receive a timely response from an upstream server it needed to access in order to complete a request. This can happen because the other server is not functioning properly, overloaded, or down.

To simplify it further, this error occurs when two servers are involved in processing a request. The first server (typically the main server) times out, waiting for a response from the second server (upstream server).

This is how the process works: every time you visit a website in your browser, the browser sends a request to the web server where the site is hosted. The server processes the request and responds with the requested resources.

Illustration of how HTTP requests and responses work
How HTTP requests and responses work.

The server response includes one of many HTTP status codes to indicate the response’s status to the browser. But not all these HTTP status codes are errors. For instance, a 200 OK status code means that the server processed the request successfully and “Everything is OK.”

The 5xx class of HTTP status codes indicates that something’s wrong with the server, the server is aware of it, and it cannot carry out the client request. As a result, they’re also referred to as Server Error 5xx status codes.

Officially, five status codes are specified under the 5xx class (500, 501, 502, 503, 504). You may come upon many unofficial codes too (506, 507, 509, 520, etc.).

The 504 Gateway Timeout error manifests itself in various forms. Here are some ways it usually shows up:

The HTTP ERROR 504 in Chrome browser
The ‘HTTP ERROR 504’ in the Chrome browser.

The 504 Gateway Timeout error is similar to the 502 Bad Gateway error, which indicates that the first server received an invalid response from the second server (upstream server).

504 GATEWAY TIMEOUT status code in Chrome DevTools
The ‘504 GATEWAY TIMEOUT’ status code in Chrome DevTools.

Variations of the 504 Gateway Timeout Error

Below are a few common 504 error message variations that you may run into:

All the above error responses, though worded differently, point to the same 504 Gateway Timeout server error.

GitHub’s customized HTTP 504 error page
GitHub’s customized HTTP 504 error page.

What Are the Causes of the 504 Gateway Timeout Error?

As the 504 error is due to a timeout between servers, the problem probably isn’t with the client’s device or internet connection. That also includes your device and connection.

A 504 Gateway Timeout error indicates that the web server is waiting too long to respond from another server and “timing out.” There can be many reasons for this timeout: the other server is not functioning properly, overloaded, or down.

The other server need not always be external (e.g. CDN, API gateway). It can also be a server-like entity within the main web server (e.g. reverse proxy server, database server).

SEO Impact of the 504 Gateway Timeout Error

For example, when Google spiders stumble upon a 503 Service Unavailable error, they’ll understand that it’s a temporary issue as it’s mostly used to enable site maintenance mode. Thus, they’ll try to crawl the page again later.

A 504 Gateway Timeout error isn’t necessarily temporary as it can be due to multiple reasons. If your site is down for just a few minutes, and if the spiders are trying to crawl it multiple times every minute, they’ll try to serve the page from their cache.  They wouldn’t even notice it.

But if your site is down for 6+ hours or more, then Google will consider the 504 error as a serious site-wide issue that you need to fix as soon as possible. This can impact your SEO negatively.

Viewing the crawl errors in Google Search Console
Viewing the crawl errors in Google Search Console

Google Search Console is one of the best SEO tools to monitor your website’s HTTP 5xx errors.

How to Fix the 504 Gateway Timeout Error?

Without knowing exact details about the site, such as its server configuration, hosting plan, third-party plugins, and the traffic it attracts, you may find it frustrating and overwhelming to fix a 504 Gateway Timeout error.

Since many variables are involved, I recommend you to start by fixing client-side issues, which are pretty rare, and then move towards fixing server-side problems. They’re usually the culprits with 504 errors.

1. Try Reloading the Webpage

One of the first things you can try when encountering a 504 Gateway Timeout error is to wait a few minutes and try reloading the page.

You can press the F5 keyboard shortcut to refresh/reload the webpage in most browsers. To remove the page’s browser cache before reloading, you can press the CTRL+F5 shortcut combo instead.

Refreshing a webpage in Chrome browser
Refreshing a webpage in Chrome browser

While you’re at it, you can also try loading the site in a different browser to rule that out as an issue. As most 504 errors are due to temporarily overloaded servers, using this solution should make your site come right back.

If waiting and reloading the site doesn’t fix the 504 error issue, you can check whether a site is down for everyone or just you. Two useful online tools to test a site for downtime are Down for Everyone or Just Me and Is It Down Right Now?

Testing Kinsta.com on Down for Everyone or Just Me
Testing Kinsta.com on Down for Everyone or Just Me

2. Reboot Your Network Devices

Sometimes, problems with your network devices like modem or router could lead to a 504 Gateway Timeout error. Rebooting these devices could help you with fixing the problem.

3. Check Your Proxy Settings

A proxy server sits between your device and the internet. It’s mostly used to enhance online privacy by hiding private information (e.g. device location) from websites and webservers (e.g. using a VPN).

While it’s rare for proxy servers to cause a 504 error, incorrect proxy server settings can sometimes be the reason. You can disable the proxy server and try reloading the webpage to see whether it’ll fix the error.

Changing the ‘Proxy’ settings in Windows 10
Changing the ‘Proxy’ settings in Windows 10

Most clients don’t use a proxy service, so you can skip this step if you’re confident that you don’t use any proxy server. However, you might have set it without you even knowing about it. I’d suggest you check your device’s and browser’s proxy settings to rule this cause out.

4. Check for DNS Issues

A 504 Gateway Timeout error can also be caused by DNS issues on the server-side or the client-side (or both).

The most probable reason for a server-side DNS issue is the FQDN (fully qualified domain name) not resolving the correct IP address or the DNS server not responding. Usually, this occurs when you’ve just migrated your site to a new server or host. Hence, it’s important to wait for the domain’s DNS records to propagate fully, which can take up to 24 hours.

You can use free tools like whatsmydns.net DNS Checker or DNSMap to see if your DNS has propagated around the globe.

Checking DNS propagation for your domain on whatsmydns.net
Checking DNS propagation for your domain on whatsmydns.net

For fixing client-side DNS issues, you could try flushing your local DNS cache. It’s like clearing your browser cache, except here, you’re flushing the DNS cache from the operating system.

ipconfig /flushdns
Flushing the DNS Cache with Command Prompt
Flushing the DNS Cache with Command Prompt in Windows

You should see a “Successfully flushed the DNS resolver Cache.” message if it worked.

sudo killall -HUP mDNSResponder

You won’t see any notification in macOS when the process finishes, but you can change that by appending the command with your custom message.

sudo killall -HUP mDNSResponder; DNS Cache was cleared successfully

Finally, you can change your client-side DNS servers temporarily. By default, your ISP assigns the DNS servers automatically to you. But you can change these to public DNS IPs temporarily.

Settings custom DNS servers in Windows 10
Settings custom DNS servers in Windows 10

5. Disable Your Site’s CDN Temporarily

Sometimes, the issue could also be with your content delivery network (CDN). If a site’s origin server isn’t reachable, most CDNs will try to serve the full webpage from their cache.

Setting the ‘Cache Everything’ page rule in Cloudflare
Setting the ‘Cache Everything’ page rule in Cloudflare

A straightforward way to troubleshoot this is to disable your CDN temporarily. For example, if you’re using the free CDN Enabler WordPress plugin to link your site assets to the CDN URLs, then you can deactivate the plugin and test reloading your site.

The same goes for using any other plugin you may use to connect to your CDN (e.g. WP Rocket, Breeze, W3 Total Cache).

Disable all plugins via SFTP by renaming the plugins folder name
Disable all plugins via SFTP by renaming the plugins folder name

504 Gateway Timeout at Cloudflare (Variation 1)

Cloudflare’s custom Error 504 screen
Cloudflare’s custom Error 504 screen

504 Gateway Timeout at Cloudflare (Variation 2)

504 Gateway Timeout error caused by Cloudflare
Error screen for 504 Gateway Timeout caused by Cloudflare
Check Cloudflare System Status at cloudflarestatus.com
Check Cloudflare System Status at cloudflarestatus.com

504 Gateway Timeout at Cloudflare Due to Large Uploads

Cloudflare’s ‘Maximum Upload Size’ limits for various plans
Cloudflare’s ‘Maximum Upload Size’ limits for various plans

6. Check Server Issues With Your Host

Server issues are one of the most common reasons for facing a 504 Gateway Timeout error. Since most WordPress sites are hosted on Nginx or Apache webservers, Nginx or Apache is waiting for a response from something and timing out.

Many clients come to Kinsta for exactly this problem they’re facing at other hosts. The conversation goes something like this:

We’re getting around 100k visitors per month with more than 200k views. Currently, we’re hosting with ____ and we experience 504 errors constantly due to server overload. I don’t like how ____ handled the problem, and we were also advised that we will have to move to their dedicated plans soon, which I believe is not necessary.

High-traffic and ecommerce sites are more prone to getting 504 errors because of server overload as they generate many uncacheable requests. However, this issue can crop with any site, including simple blogs. Many hosts will ask you to upgrade to a high-tier plan to fix the issue, which in most cases is unnecessary.

Apart from isolating each site in its container, Kinsta has also designed its infrastructure to handle thousands of concurrent connections easily. Kinsta even hosts the MySQL databases at localhost, not a remote server. This means no latency between machines, resulting in faster queries and fewer chances of timeouts occurring.

Many clients who migrate to Kinsta see huge decreases in overall load times.

A 212.5% increase in performance after switching to C2.
A 212.5% increase in performance after switching to C2.

An overloaded server isn’t the only cause for a server timeout. There can be many other reasons for the 504 error:

Slow Server Infrastructure

The server you use to host your site may not have enough resources to handle the load. It’s like playing a modern, graphics-intensive videogame on a decade-old PC.

The server just hangs up trying to serve the website. The only solution to this problem is to upgrade to a server with better infrastructure. For this reason, even Kinsta’s most basic hosting plan will handle a static site with medium traffic.

Needs More PHP Workers

PHP workers are used to execute your site’s code. An ecommerce site that gets 50,000 visitors per month needs a lot more resources than a simple blog with the same amount of traffic. If all the server’s PHP workers are busy, they’ll build up a queue.

When the queue gets too big, the server disregards old requests, which may cause the server to throw up a 504 gateway error. You can ask your host about increasing your number of PHP workers. This’ll allow your site to execute multiple requests simultaneously.

Firewall Issues

Your server’s firewall could have some errors or an improper configuration. Perhaps, a few of its rules prevent the server from establishing a connection properly. To know if your firewall is the culprit, you can check your server’s error logs.

Network Connectivity Problems

Connectivity issues between the proxy server and the web server could cause delays in responding to HTTP requests. If you use a load balancer, there could also be network connectivity issues with it.

HTTP Timeouts

HTTP timeouts can occur when a connection between the web server and the client is kept open for too long. With WordPress sites, this usually happens when running WordPress imports. One way to resolve this issue is to switch to a faster internet connection.

You can also use a tool with support for WP-CLI to run the scripts directly on the server, bypassing the HTTP connection entirely. For instance, you can use the wp import WP-CLI command to run the WordPress Importer plugin directly through the command-line interface.

Important: 504 Gateway Timeout errors look similar to 503 Service Unavailable errors or 502 Bad Gateway errors. But they’re all different. If you’re experiencing a 504 error at Kinsta, open a support ticket to get your issue fixed immediately.

For monitoring your site’s downtime on your own, you can use a tool like updown.io. It’ll check your website’s status (or any URL) periodically by sending an HTTP request to it. You can set the check frequency from 15 seconds to 1 hour. If your website isn’t responding correctly, it’ll notify you with an email or an SMS.

Monitor your website with updown.io
Monitor your website easily with updown.io

You’ll get a generous quantity of free credits with every account of updown.io, but if you’re looking for cheaper alternatives, you can check out WebGazer or UptimeRobot. Both these tools will help you monitor your site’s uptime every 5 minutes for free. That’s decent enough for most website owners.

WebGazer website monitoring tool's dashboard
WebGazer website monitoring tool’s dashboard

For a detailed explanation, check out Kinsta’s post on the importance of managed WordPress hosting.

7. Check for Spam, Bots, or DDoS Attacks

You can look at your server traffic and analytics to see if you can spot any irregular patterns in the site traffic. If you’re using Kinsta to host your site, you can view this data easily by going to your MyKinsta Analytics dashboard.

Screenshot: Site-level Analytics in MyKinsta.
Site-level Analytics in MyKinsta.

Start your investigation by looking at the top client IPs. It’ll give you an idea of who generates the maximum number of requests, and from where. If your server suddenly uses up enormous bandwidth or attracts a lot of traffic, then this report will come in super handy.

Screenshot: Top client IPs displayed in MyKinsta Analytics dashboard.
Top client IPs displayed in Analytics dashboard.

Next, you can check out the Cache Analysis report. Here, you can see how many requests are bypassing or missing the cache, or being served from the cache. For performance and stability reasons, you want to cache as many requests as possible, but it’s not always possible to achieve that.

For example, WooCommerce sites generate many uncacheable requests for features such as the shopping cart and the checkout process.

The ‘Cache Analysis’ screen in MyKinsta
The ‘Cache Analysis’ screen in MyKinsta

8. Repair Your Corrupted WordPress Database

Sometimes, a 504 Gateway Timeout error can be because of a corrupt database, especially in WordPress sites. Typically, this is due to corrupted database tables or files. Sometimes, it can also be caused by a serious security issue like your site or database being hacked.

Repairing a corrupted WordPress database depends on the problem. Plugins like WP-DBManager make it easy to diagnose database issues and repair them. I recommend you to read Kinsta’s detailed walkthrough on repairing WordPress database issues to get started.

9. Check Your Site’s Plugins and Themes

In most cases, third-party plugins and themes don’t cause 504 errors. But there’s a slight chance that they might cause server timeouts, usually by queuing up many uncached requests generated by the plugin/theme. As this ties up a lot of your server’s PHP workers, it can cause 504 errors.

A great example of this issue is WooCommerce, a plugin installed to add ecommerce functionality to WordPress sites.

The simplest way you can troubleshoot this problem is by deactivating all your plugins. Remember, you won’t lose any data if you just deactivate a plugin.

Deactivate plugins in WordPress
Deactivating all the WordPress plugins through WP admin dashboard

Once you’ve deactivated all the plugins, check whether your site loads properly. If it works, you must activate each plugin, testing the site after enabling every plugin.

Finally, make sure that your plugins, themes, and WordPress core are up to date. Also, ensure that your server is running the recommended version of PHP.

If you feel this to be too overwhelming, you can always reach out to your host for help. Kinsta uses Kinsta APM and other troubleshooting techniques to help clients narrow down what plugin, query, or script might cause the error.

In the worst-case scenarios, like an inefficient query or bad code in a plugin/theme, you can bring in a WordPress developer to fix the issue.

10. Check Error Logs

Viewing error logs can be very helpful when troubleshooting and debugging 504 errors on your site. This can help you narrow down an issue on your site quickly, especially if it’s resulting from a demanding plugin on your site.

If you’re a Kinsta customer, you can easily see logged errors in the MyKinsta dashboard. Start by selecting WordPress Sites in the sidebar menu, choose the site you want to examine, then select Logs to open the Log viewer page.

Screenshot: Viewing the error log within the MyKinsta dashboard.
Viewing the error.log file within the MyKinsta dashboard.
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

The WP_DEBUG constant enables or disables the WordPress debug mode. It has two optional companion constants that can extend its features. The WP_DEBUG_LOG constant directs all errors to be saved to a debug.log file within the /wp-content/ directory. If you don’t see this file, you can always create one.

The WP_DEBUG_DISPLAY constant controls whether debug logs show up on the HTML page. Setting this to false will hide all errors, but you can review the errors later, as you’ve also defined WP_DEBUG_LOG as true.

Important: If you have WP_DEBUG enabled in the Kinsta environment, it’ll route all errors to the debug.log file and not the error.log in the MyKinsta dashboard.

You can also download the raw WordPress error log files via SFTP. Typically, you can find error logs in your server’s root directory in a folder named “logs.”

Accessing the WordPress error logs folder via SFTP
Accessing the WordPress error logs folder via SFTP

Lastly, you can check the server log files. Depending on which server you’re using to host your WordPress site, they’re commonly found in these locations:

  • Apache: /var/log/apache2/error.log/
  • Nginx: /var/log/nginx/error.log/

11. Configure Apache or Nginx Settings Properly

You can edit your server config files to increase resource limits for specific directives. This can help you resolve the 504 Gateway Timeout error.

For Apache Webservers

TimeOut 600

This setting defines how long the server will wait for certain requests before marking it as a network timeout issue. Its default value is 60 seconds (Apache 2.4 version).

max_execution_time 300

The default value of PHP’s max_execution_time directive is 30 seconds. Increasing it will allow your site’s PHP scripts to run longer.

For Nginx Webservers

If you’re running your WordPress sites on Nginx + FastCGI Process Manager (PHP-FPM) or using Nginx as a reverse proxy for Apache, you can tweak the server settings to help prevent 504 Gateway Timeout errors.

504 Gateway Timeout Error on Nginx + FastCGI (PHP-FPM)
sudo nano /etc/php/7.2/fpm/pool.d/www.conf
request_terminate_timeout = 300

After this, you must edit your php.ini file. You can locate it at /etc/php.ini. Open the file and add/change the value for the max_execution_time directive to 300 seconds.

max_execution_time = 300
location ~ .php$ {
...
fastcgi_read_timeout 300;
}

Reload Nginx and PHP-FPM for the changes to take effect.

sudo service nginx reload
sudo service php7.4-fpm reload

The exact code to reload PHP-FPM will vary based on the PHP version installed on your server. Test your site to see whether it has fixed the issue.

504 Gateway Timeout Error on Nginx Proxy
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;

Don’t forget to reload Nginx after making your changes.

sudo service nginx reload

Other HTTP Errors Like 504 Gateway Timeout

As mentioned earlier in the article, many other HTTP 5xx errors are just like the 504 Gateway Timeout error. It’s because they all happen on the server-side. These errors include:

When you don’t know what caused a 504 Gateway Timeout error, how do you fix it in time to keep hard-earned visitors from bouncing to competitor sites? 🤷‍♂️ All the details are in this post. ⬆️Click to Tweet

Summary

Your site can be affected by the 504 Gateway Timeout error because of multiple reasons. In this article, you learned how to troubleshoot them all. Typically, these errors are caused due to server-side issues, in which case you can reach out to your host and get it resolved quickly.

However, you must also understand that this error can be due to third-party plugins, themes, services, inefficient database queries, or a combination of two or more of these. If you’re maxing out your server’s resources (e.g. PHP workers), it’s recommended to optimize your site for performance.

If you still find that your website is timing out, then it might very well be that you need to upgrade your hosting plan or the number of PHP workers. I recommend you to consider this option only after you’ve exhausted all the other solutions described in this article.

Did we miss anything? If you’re still finding it difficult to fix the 504 Gateway Timeout error on your site, leave a comment below.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Get started with a free trial of our Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Читайте также:  Оптимизируйте настройку: с легкостью загрузите ISO для виртуальной машины
Оцените статью
Хостинги