Api ошибка 502

Adding an API Gateway to your application is a good way to centralize some work you usually have to do for all of your API routes, like authentication or validation. But like every software system, it comes with its own problems. Solving errors in the cloud isn’t always straightforward, and API Gateway isn’t an exception.

What is AWS API Gateway?

AWS API Gateway is an HTTP gateway, and as such, it uses the well-known HTTP status codes to convey its errors to you. Errors in the range of 400 to 499 usually point to a problem with the API client, and errors in the range of 500 to 599 mean something on the server is wrong.

This is a rule of thumb, and if you don’t have any logic bugs in your backend, it holds. But nobody is perfect, and so it could happen that a 400 code still means your client is right and your backend is wrong. But let’s not get ahead of us and look into the errors, case by case.

what is aws ap gateway

Handling API Gateway 400 Error: Bad Request

The 400 error is probably the broadest of the client errors. Depending on what AWS service API Gateway is integrating with for the URL, it can mean many things.

A retry usually doesn’t help because it means the request doesn’t match what that specific API Gateway integration is expecting, and sending it again wouldn’t change that.

Reasons for this error include:

  • Invalid JSON, like missing commas and such.
  • Missing fields, when the upstream service has required a field you missed
  • Wrong data types, when you send a string instead of a number
  • Invalid characters, like using whitespaces in identifiers

You can find the required fields, expected data types, and valid characters for a field in the documentation of the AWS service you integrated with API Gateway.

Handling API Gateway 403 Error: Access Denied

This error is also known as “Forbidden” and implies some permission issue. Every resource you provision in AWS has an IAM role. This role defines what that resource can access and how it can access it. Your API Gateway has an IAM role too, and if it’s not configured correctly, it can prevent API Gateway from integrating with a service.

Again, a retry doesn’t help here.

If you use end-user authentication with AWS Cognito, every request will get a temporary role related to the Cognito user who issued the request. If this role isn’t configured correctly, it can also prevent users from accessing specific resources.

If you’re using a custom Lambda authorizer in your API Gateway, this error code could also relate to a problem in that Lambda function.

Handling API Gateway 404 Error: Not Found

The 404 error usually means your URL is wrong. Probably in 99% of the cases

If you’re sure the URL is right, but you’re still getting the error, it could also be related to the service you integrate with API Gateway when you try to access data in these services that aren’t there.

A retry only solves this problem if the 404 comes from a race condition. When you told the backend to create a resource, you wanted to access it with the next request, but the request was too soon, and the thing you created isn’t there yet. Such issues happen with eventually consistent data stores like DynamoDB. 

The more expensive consistent reads of DynamoDB usually solve this problem.

Handling API Gateway 409 Error: Conflict

The 409 status indicates that your request is trying to do something that conflicts with a resource’s current state. A resource could be a record in a DynamoDB table that’s integrated with your API. It could be that you tried to create a resource with a specific ID that already exists.

The 409 error is also related to something called a callers reference. This reference is used to mark a request, so it gets only executed once. If you send it and don’t get an answer from the API, you don’t know if the request got lost before or after it made its way to the API. This usually leads to a retry. If the API hasn’t seen the caller reference the last time, it will simply execute it and respond with an appropriate status code. But if the API has seen the caller reference, it gives you a 409 status code to indicate your request was already accepted when you sent it the first time.

So, a retry usually won’t solve this problem and can even be the source of this error code in the first place.

Handling API Gateway 429 Error: Limit Exceeded

There are two 429 errors you could get from API Gateway. The first one is called “Limit Exceeded Exception,” which indicates that you went over an API quota.

API Gateway allows access control via API keys. When creating such a key, you can also define a usage quota such as 1000 requests per week. If this quota is reached, the API gateway will respond with a 429.

Normally a retry doesn’t solve this problem. You either have to increase the quota for the key, or you have to wait until the next usage period starts.

The best way to get around this issue is to keep your API requests monitored and counted. Check how many requests you send and if you really need to send so many. You can also try to cache responses so that you can reuse them instead of sending duplicate requests that count to your key’s quota. 

Handling API Gateway 429 Error: Too Many Requests

The second 429 error is of temporary nature. You would get it if you sent too many requests at once. For example, if you have an API endpoint connected to a Lambda function, this function has a predefined limit of 1000 concurrent invocations.

If you send 1001 in parallel, you get a 429 error, but depending on the time this Lambda function takes to handle a request, you can retry some time later and get a free slot again.

Again, API keys can have limits too. If you got a key that only allows for 10 concurrent requests, the upstream service could handle millions, but your 11th parallel request wouldn’t go through.

Try to monitor your request so you see when they get close to the limit of your services, and try to cache requests on your clients so that they won’t hammer the API.

api gateway detecting issues

Did you know Dashbird will detect API Gateway issues and alert them to you?

Handling API Gateway 500 Error: Internal Server Error

The 500 status code might be the most used and most generic HTTP error on this planet. If you get it from an API endpoint that integrates with AWS Lambda, it usually means your code buggy.

The next source for this error is inconsistent error mapping. Many of the errors we talked about here can become a 500 error when finally landing on your client as a response. You’ll get a “limit exceeded,” but it will have a 500 status code instead of 429. So you have to extract the right error out of this response, check what the real cause is, and then look at how to solve it.

Since the error can be anything really, a retry can technically solve that problem, but usually, it doesn’t.

If you monitor your system carefully and get one of these every few million requests, it could be that cosmic rays flipped some bits or whatever. Still, if you see a 500 status code more often than that, it’s crucial to investigate; it can very well point to an inconsistency that will blow up sooner or later.

Handling API Gateway 502 Error: Bad Gateway

A 502 error code is related to the service your API Gateway integrates with. It means that API Gateway couldn’t understand the response.

For example, when you throw an error in a Lambda function or the resolved value has an invalid structure, it can lead to a 502 error. If you used EC2 or ECS/EKS, it could also be that API Gateway can’t connect to the VM or container because they aren’t running (correctly).

Retries can help, especially when integrated services are currently restarting. 

Handling API Gateway 503 Error: Service Unavailable

If you see a 503 error, most of the time, it means the service you’re integrating takes too long to answer. 

API Gateway has a maximum hard limit of 30 seconds timeouts. If your service can’t respond in under 30 seconds, API Gateway will assume it’s unavailable and stop waiting.

If the work your service does takes around 30 seconds, you should handle things asynchronously. Respond with a 202 accepted and give the client a way to fetch the results later.

If your service usually responds well below 30 seconds but only occasionally goes over the limit, you can solve the problem with retries.

Handling API Gateway 504 Error: Endpoint Request Timed-out 

The 504 status code is a bit like 503. The difference is that 504 indicates a DNS or network problem, and 503 indicates a performance problem.

Again, this can be temporary, and a retry might solve it. After all, the internet isn’t 100% stable. 

But you usually see that issue when an integrated service isn’t running, or you got the IP or hostname wrong, either because you entered the wrong or they changed somehow after you entered them.

Conclusion

We went over all the API Gateway errors you will probably encounter, and like with anything debugging-related, things can get quite messy — especially if you have countless rows of logs to sift through.

api gateway metrics dashboard

The good news is that Dashbird integrates well with API Gateway monitoring and delivers actionable insights straight to your Slack or SMS when things go awry. 

Dashbird also works with AWS as their Advanced Technology Partner and uses the AWS Well-Architected Framework to ensure you’re on track to performance and cost optimization. If you want to try Dashbird out, it’s free for the first 1 million invocations per month.

Read our blog

Introducing easy custom event monitoring for serverless applications.

Today we are excited to announce scheduled searches – a new feature on Dashbird that allows you to track any log event across your stack, turn it into time-series metric and also configure alert notifications based on it.

Why and How to Monitor Amazon OpenSearch Service

One of the most vital aspects to monitor is the metrics. You should know how your cluster performs and if it can keep up with the traffic. Learn more about monitoring Amazon OpenSearch Service.

Why and How to Monitor AWS Elastic Load Balancing

Dashbird recently added support for ELB, so now you can keep track of your load balancers in one central place. It comes with all the information you expect from AWS monitoring services and more!

More articles

I have an API Gateway with a LAMBDA_PROXY Integration Request Type. Upon calling context.succeed in the Lambda, the response header is sent back with code 302 as expected (shown below). However, I want to handle 500 and 404 errors, and the only thing I am sure about so far, is that I am returning the error incorrectly as I am getting 502 Bad Gateway. What is wrong with my context.fail?

Here is my handler.js

const handler = (event, context) => { 
    //event consists of hard coded values right now
    getUrl(event.queryStringParameters)
    .then((result) => {
        const parsed = JSON.parse(result);
        let url;
        //handle error message returned in response
        if (parsed.error) {
            let error = {
                statusCode: 404,
                body: new Error(parsed.error)
            }
            return context.fail(error);
        } else {
            url = parsed.source || parsed.picture;
            return context.succeed({
                statusCode: 302,
                headers: {
                  Location : url
                }
              });
        }
    });
};

Ricardo's user avatar

Ricardo

3,5764 gold badges36 silver badges49 bronze badges

asked Mar 17, 2017 at 2:01

johnny_mac's user avatar

If you throw an exception within the Lambda function (or context.fail), API Gateway reads it as if something had gone wrong with your backend and returns 502. If this is a runtime exception you expect and want to return a 500/404, use the context.succeed method with the status code you want and message:

if (parsed.error) {
  let error = {
    statusCode: 404,
    headers: { "Content-Type": "text/plain" } // not sure here
    body: new Error(parsed.error)
}
return context.succeed(error);

answered Mar 17, 2017 at 2:34

Stefano Buliani's user avatar

0

I had the same problem, in my case the issue was that my function was not returning anything in context.done(). So instead of context.done(null), I did context.done(null, {});

answered Aug 21, 2017 at 21:04

Sello Mkantjwa's user avatar

Sello MkantjwaSello Mkantjwa

1,7681 gold badge20 silver badges36 bronze badges

I’ve gotten 502’s from multiple things. Here are the ones I have figured out so far.

Answer 1:

claudia generate-serverless-express-proxy --express-module {src/server?}
If you are not using claudia and express, this answer won’t help you.

Answer 2:

Lambda function->Basic Settings->Timeout. Increase it to something reasonable. It defaults to 3 seconds. But the first time building it typically takes longer.

answered Dec 12, 2018 at 2:16

Michael's user avatar

MichaelMichael

1,14715 silver badges15 bronze badges

1

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

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

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

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

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

Подписаться

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

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

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

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

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

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

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

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

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

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

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

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

ipconfig /flushdns

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

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

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

Для Ubuntu:

sudo service network-manager restart

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

sudo /etc/init.d/nscd restart

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

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

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

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

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

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

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

Ошибка 400 Bad Request

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

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

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

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

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

define( 'WP_DEBUG', true );

define( 'WP_DEBUG_LOG', true );

define( 'WP_DEBUG_DISPLAY', false );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sorry I thought It would be an easy fix :(

From the first command (rebuild php service)

docker-compose build php
Building php
Step 1/29 : ARG PHP_VERSION=7.3
Step 2/29 : ARG NGINX_VERSION=1.15
Step 3/29 : ARG VARNISH_VERSION=6.2
Step 4/29 : FROM php:${PHP_VERSION}-fpm-alpine AS api_platform_php
 ---> 5272cea79594
Step 5/29 : RUN apk add --no-cache              acl             file            gettext                 git     ;
 ---> Using cache
 ---> 05b3cabc4b44
Step 6/29 : ARG APCU_VERSION=5.1.17
 ---> Using cache
 ---> 93184c275bea
Step 7/29 : RUN set -eux;       apk add --no-cache --virtual .build-deps                $PHPIZE_DEPS            icu-dev                 libzip-dev              postgresql-dev        zlib-dev         ;               docker-php-ext-configure zip --with-libzip;     docker-php-ext-install -j$(nproc)               intl            pdo_pgsql               zip     ;     pecl install             apcu-${APCU_VERSION}    ;       pecl clear-cache;       docker-php-ext-enable           apcu            opcache         ;               runDeps="$(           scanelf --needed --nobanner --format '%n#p' --recursive /usr/local/lib/php/extensions                    | tr ',' 'n'                   | sort -u                       | awk 'system("[ -e /usr/local/lib/" $1 " ]") == 0 { next } { print "so:" $1 }'        )";     apk add --no-cache --virtual .api-phpexts-rundeps $runDeps;             apk del .build-deps
 ---> Using cache
 ---> b8c46a7b7a4d
Step 8/29 : COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
 ---> Using cache
 ---> 24adbce067b1
Step 9/29 : RUN ln -s $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini
 ---> Using cache
 ---> 7588898e88ff
Step 10/29 : COPY docker/php/conf.d/api-platform.ini $PHP_INI_DIR/conf.d/api-platform.ini
 ---> Using cache
 ---> 803e6f14a94b
Step 11/29 : ENV COMPOSER_ALLOW_SUPERUSER=1
 ---> Using cache
 ---> 93e2c95176d1
Step 12/29 : RUN set -eux;      composer global require "symfony/flex" --prefer-dist --no-progress --no-suggest --classmap-authoritative;       composer clear-cache
 ---> Using cache
 ---> ef341c043c7c
Step 13/29 : ENV PATH="${PATH}:/root/.composer/vendor/bin"
 ---> Using cache
 ---> 9dc5e53e6f7b
Step 14/29 : WORKDIR /srv/api
 ---> Using cache
 ---> 0231e3a76386
Step 15/29 : ARG APP_ENV=prod
 ---> Using cache
 ---> 4b076ae67326
Step 16/29 : COPY composer.json composer.lock symfony.lock ./
 ---> Using cache
 ---> 940474935990
Step 17/29 : RUN set -eux;      composer install --prefer-dist --no-dev --no-scripts --no-progress --no-suggest;        composer clear-cache
 ---> Using cache
 ---> 8efa473898b3
Step 18/29 : COPY .env ./
 ---> Using cache
 ---> 25646ceadcca
Step 19/29 : RUN composer dump-env prod;        rm .env
 ---> Using cache
 ---> 659ce564ca84
Step 20/29 : COPY bin bin/
 ---> Using cache
 ---> 8967b1a9b1e5
Step 21/29 : COPY config config/
 ---> Using cache
 ---> fb8ba186d3be
Step 22/29 : COPY public public/
 ---> Using cache
 ---> bbe5c275b1e9
Step 23/29 : COPY src src/
 ---> Using cache
 ---> fe16a90fc02d
Step 24/29 : RUN set -eux;      mkdir -p var/cache var/log;     composer dump-autoload --classmap-authoritative --no-dev;       composer run-script --no-dev post-install-cmd;  chmod +x bin/console; sync
 ---> Using cache
 ---> 01d5c399d4f2
Step 25/29 : VOLUME /srv/api/var
 ---> Using cache
 ---> 9f0fca148aa2
Step 26/29 : COPY docker/php/docker-entrypoint.sh /usr/local/bin/docker-entrypoint
 ---> f91217b26fbd
Step 27/29 : RUN chmod +x /usr/local/bin/docker-entrypoint
 ---> Running in 06413fdc2f00
Removing intermediate container 06413fdc2f00
 ---> bb1842e0447f
Step 28/29 : ENTRYPOINT ["docker-entrypoint"]
 ---> Running in d4ffec6ff3d5
Removing intermediate container d4ffec6ff3d5
 ---> b351375e1e47
Step 29/29 : CMD ["php-fpm"]
 ---> Running in 2a4af9df0e4d
Removing intermediate container 2a4af9df0e4d
 ---> d8931f4db99b

Successfully built d8931f4db99b
Successfully tagged quay.io/api-platform/php:latest

Then

docker-compose up -d
api-platform_admin_1 is up-to-date
api-platform_client_1 is up-to-date
api-platform_mercure_1 is up-to-date
api-platform_db_1 is up-to-date
Recreating api-platform_php_1 ... done
Recreating api-platform_api_1 ... done
Recreating api-platform_cache-proxy_1 ... done
Recreating api-platform_h2-proxy_1    ... done
docker-compose logs -f php       
Attaching to api-platform_php_1
php_1          | Reading ./composer.json
php_1          | Loading config file ./composer.json
php_1          | Checked CA file /etc/ssl/certs/ca-certificates.crt: valid
php_1          | Executing command (/srv/api): git branch --no-color --no-abbrev -v
php_1          | Executing command (/srv/api): git describe --exact-match --tags
php_1          | Executing command (/srv/api): git log --pretty="%H" -n1 HEAD
php_1          | Executing command (/srv/api): hg branch
php_1          | Executing command (/srv/api): fossil branch list
php_1          | Executing command (/srv/api): fossil tag list
php_1          | Executing command (/srv/api): svn info --xml
php_1          | Reading /root/.composer/composer.json
php_1          | Loading config file /root/.composer/composer.json
php_1          | Reading /srv/api/vendor/composer/installed.json
php_1          | Reading /root/.composer/vendor/composer/installed.json
php_1          | Loading plugin SymfonyFlexFlex
php_1          | Reading /root/.composer/cache/repo/https---flex.symfony.com/versions.json from cache
php_1          | Downloading https://flex.symfony.com/versions.json
php_1          | Downloading https://flex.symfony.com/versions.json
php_1          | Downloading https://flex.symfony.com/versions.json
php_1          | "https://flex.symfony.com/versions.json" does not contain valid JSON
php_1          | Parse error on line 1:
php_1          | 
php_1          | ^
php_1          | Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
php_1          | https://flex.symfony.com/versions.json could not be fully loaded, package information was loaded from the local cache and may be out of date
php_1          | Restricting packages listed in "symfony/symfony" to "4.3.*"
php_1          | Running 1.8.6 (2019-06-11 15:03:05) with PHP 7.3.7 on Linux / 5.0.0-20-generic
php_1          | Reading ./composer.lock
php_1          | Loading composer repositories with package information
php_1          | Installing dependencies (including require-dev) from lock file
php_1          | Reading ./composer.lock
php_1          | Resolving dependencies through SAT
php_1          | Looking at all rules.
php_1          | 
php_1          | Dependency resolution completed in 0.002 seconds
php_1          | 
php_1          | Prefetching 15 packages 🎶 💨
php_1          |   - DownloadingDownloading https://codeload.github.com/thephpleague/html-to-markdown/legacy.zip/250d1bf45f80d15594fb6b316df777d6d4c97ad1
php_1          | Downloading https://codeload.github.com/symfony/stopwatch/legacy.zip/6b100e9309e8979cf1978ac1778eb155c1f7d93b
php_1          | Downloading https://codeload.github.com/symfony/process/legacy.zip/856d35814cf287480465bb7a6c413bb7f5f5e69c
php_1          | Downloading https://codeload.github.com/symfony/options-resolver/legacy.zip/914e0edcb7cd0c9f494bc023b1d47534f4542332
php_1          | Downloading https://codeload.github.com/PHP-CS-Fixer/diff/legacy.zip/78bb099e9c16361126c86ce82ec4405ebab8e756
php_1          | Downloading https://codeload.github.com/composer/xdebug-handler/legacy.zip/46867cbf8ca9fb8d60c506895449eb799db1184f
php_1          | Downloading https://codeload.github.com/composer/semver/legacy.zip/46d9139568ccb8d9e7cdd4539cab7347568a5e2e
php_1          | Downloading https://codeload.github.com/FriendsOfPHP/PHP-CS-Fixer/legacy.zip/20064511ab796593a3990669eff5f5b535001f7c
php_1          | Downloading https://codeload.github.com/njh/easyrdf/legacy.zip/acd09dfe0555fbcfa254291e433c45fdd4652566
php_1          | Downloading https://codeload.github.com/api-platform/schema-generator/legacy.zip/849d34cc19fd86851d3015a8cbd3d8fe00da3ef8
php_1          | Downloading https://codeload.github.com/nikic/PHP-Parser/legacy.zip/1bd73cc04c3843ad8d6b0bfc0956026a151fc420
php_1          | Downloading https://codeload.github.com/symfony/maker-bundle/legacy.zip/d262c2cace4d9bca99137a84f6fc6ba909a17e02
php_1          | Downloading https://codeload.github.com/symfony/var-dumper/legacy.zip/f974f448154928d2b5fb7c412bd23b81d063f34b
php_1          | Downloading https://codeload.github.com/symfony/web-profiler-bundle/legacy.zip/ca3a3c8558bc641df7c8c2c546381ccd78d0777a
php_1          | Downloading https://codeload.github.com/symfony/profiler-pack/legacy.zip/99c4370632c2a59bb0444852f92140074ef02209

And nothing else when pressing F5 serveral times…

I also tried to install symfony/flex from inside another docker service and it works perfectly…

docker-compose exec web /bin/bash
root@669a8bf34e5f:/var/www# composer require symfony/flex
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Using version ^1.4 for symfony/flex
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Restricting packages listed in "symfony/symfony" to "4.3.*"
Package operations: 0 installs, 1 update, 0 removals
  - Updating symfony/flex (v1.4.4 => v1.4.5): As there is no 'unzip' command installed zip files are being unpacked using the PHP zip extension.
This may cause invalid reports of corrupted archives. Besides, any UNIX permissions (e.g. executable) defined in the archives will be lost.
Installing 'unzip' may remediate them.
Downloading (100%)         
Writing lock file
Generating autoload files
ocramius/package-versions:  Generating version class...
ocramius/package-versions: ...done generating version class
Executing script cache:clear [OK]
Executing script assets:install public [OK]

Ошибка 502 — что значит и как исправить? Об этом расскажем в статье.

  • Ошибка 502 Bad Gateway: что значит
  • Ошибка 502 при открытии сайта: причины возникновения
  • Как владельцу сайта исправить ошибку 502
    • Способ 1
    • Способ 2
  • Как исправить ошибку 502: советы для пользователей
  • Как очистить кеш DNS

Ошибка 502 Bad Gateway: что значит

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

Ошибка шлюза 502 может возникнуть при неправильной работе:

  • сервера, на котором размещен сайт,
  • DNS-сервера,
  • прокси-сервера.

Проблема может наблюдаться как на всем сайте, так и на отдельных страницах. Это зависит от причины возникновения ошибки. У ошибки 502 есть разновидности: Bad Gateway Nginx и Bad Gateway Apache. Также эта ошибка может называться:

  • Error 502,
  • Bad 502 Gateway,
  • 502 Error,
  • Bad Gateway: Registered endpoint failed to handle the request, Temporary Error (502),
  • 502 Proxy Error,
  • HTTP 502,
  • 502. That’s an error,
  • 502 Service Temporarily Overloaded,
  • 502 Server Error: The server encountered a temporary error and could not complete your request,
  • 502 – Web server received an invalid response while acting as a gateway or proxy server,
  • HTTP Error 502 Bad Gateway.

Ошибка 502 при открытии сайта: причины возникновения

Чаще всего ошибка 502 возникает из-за перегрузки сервера. Причины перегрузки могут быть следующими:

  • большое количество посетителей. Возможности сервера ограниченны, поэтому одновременно посещать сайт может лишь ограниченное число пользователей. Максимально допустимая нагрузка на сервер зависит от его мощности и настроек, которые внес владелец ресурса. Если на сайт одновременно зашло слишком много пользователей, сервер не выдержит нагрузки и возникнет код ошибки 502;
  • DDoS-атака. Хакеры создают большое количество запросов на сервер, как при большом наплыве посетителей. Из-за этого сервер не выдерживает нагрузки и выходит из строя;
  • сайт плохо оптимизирован. Ресурс может быть настроен так, что небольшое количество пользователей генерирует много запросов. В таком случае владельцу ресурса нужно оптимизировать работу сервера с запросами пользователей. 

Также причиной возникновения 502 Gateway Error могут быть ошибки PHP. Проблемы в работе могут вызывать некорректно настроенные плагины и ошибки в коде сайта.

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

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

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

Прежде всего проверьте количество свободной оперативной памяти. Сделать это можно двумя способами.

Способ 1:

  1. Подключитесь к серверу по SSH.
  2. В терминале введите команду top:

MiB Mem ― вся оперативная память.
MiB Swap ― раздел подкачки.

Найдите строку MiB Mem — free. Это количество свободной оперативной памяти на сервере. Если ее мало, ошибка возникает из-за нехватки памяти. Чтобы решить проблему, увеличьте количество оперативной памяти.

Способ 2:

  1. Подключитесь к серверу по SSH.
  2. В терминале введите команду free -m:

Mem ― вся оперативная память.
Swap ― раздел подкачки.

Найдите строку Mem — free. В ней указано количество свободной оперативной памяти на сервере. Если ее мало, ошибка возникает из-за нехватки памяти. Чтобы решить проблему, увеличьте количество оперативной памяти.

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

Проверьте логи сервера. Если проблема возникла после обновлений на сайте, посмотрите журнал изменений и отмените доработки, которые вызвали сбои на сервере. Помимо этого, в логах можно увидеть DDoS-атаку. Если вы увидели ошибку «OOM (out of memory)», то причина в нехватке памяти.

Проверьте корректность работы вспомогательных служб, таких как MySQL и Memcached. Их неправильная работа может стать причиной 502 ошибки. 

Если ваш сайт сделан на WordPress, попробуйте отключить плагины. Они могут влиять на работу сервера. Чтобы отключить плагин:

  1. Войдите в административную панель по адресу домен/wp-admin.php.
  2. Перейдите в раздел «Плагины» ― «Установленные».
  3. Нажмите «Деактивировать»:

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

На VPS и выделенных серверах проблема может возникнуть из-за некорректной работы бэкенд-сервера (например, Apache). Если Nginx не может получить ответ от этого сервиса, возникнет 502 ошибка. Владельцы сайта сталкиваются с ошибкой, когда:

  • какой-то сервис выключен. Перезапустите веб-сервер Apache, PHP-FPM, Gunicorn, NodeJS или другой сервис, с которым работает Nginx;
  • связь между Nginx и бэкенд-сервером настроена неправильно. Например, Nginx обращается к порту 8080, а веб-сервер Apache «слушает» другой порт. В таком случае нужно изменить настройки веб-сервера.

Если вы не смогли самостоятельно исправить ошибку 502, обратитесь в службу технической поддержки. Подробно опишите возникшую проблему и действия, которые вы предпринимали для ее устранения. Укажите время, в которое наблюдалась ошибка, и название сайта. Если ошибка возникает после выполнения каких-либо действий (отправка формы, добавление файлов), опишите порядок действий для воспроизведения проблемы.

Как исправить ошибку 502: советы для пользователей

Если вы пользователь и видите на сайте ошибку 502, проделайте следующие действия:

  1. Обновите страницу. Если ошибка возникла из-за большого наплыва посетителей, вероятно, что спустя время пользователи уйдут, нагрузка спадет и сайт откроется.
  2. Попробуйте открыть другой сайт. Если на других ресурсах ошибка не возникает, значит проблема на стороне владельца сайта. В таком случае вы ничего не можете сделать. Нужно ожидать, когда владелец веб-ресурса устранит проблему.
  3. Проверьте интернет-соединение. Из-за нестабильного подключения к сети и низкой скорости интернета браузер может не получить данные с сервера.
  4. Откройте браузер в режиме «Инкогнито». В «Инкогнито» браузер работает без расширений. Если в этом режиме сайт открылся без ошибки, то какое-то из установленных расширений мешает соединению. Это расширение нужно отключить.
  5. Очистите кеш и куки. Возможно, проблема уже устранена и сайт работает корректно, но браузер открывает старую версию страницы из кеша.
  6. Очистите кеш DNS. DNS-кеш хранит IP-адреса ранее посещенных сайтов локально на устройстве, чтобы ускорить связь с сервером и открывать веб-страницы быстрее. Если у сайта изменились DNS и кеш отправляет вас по старому IP-адресу, возникнет ошибка 502. Для исправления ошибки нужно очистить кеш DNS.

Как очистить кеш DNS

Способ чистки DNS-кеша зависит от вашей операционной системы. Ниже мы описали, как очистить DNS-кеш на Windows, Linux и MacOS.

Windows

  1. Откройте командную строку. Для этого нажмите Win+R, введите «cmd» и нажмите OK:

  1. Введите команду: ipconfig /flushdns
  2. Дождитесь оповещения об успешной очистке кеша:

Linux

  1. Откройте терминал при помощи сочетания клавиш Ctrl+Alt+T.
  2. Введите команду:
  • Для Ubuntu:

sudo service network-manager restart

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

sudo /etc/init.d/nscd restart
 

MacOS

  1. Откройте терминал. Для этого нажмите Command+Space, введите «Терминал» и кликните по найденному приложению.
  2. Введите команду:

sudo killall -HUP mDNSResponder

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Apex ошибка engine error audio
  • Apple music ошибка 66681
  • Apple music 22950 ошибка
  • Apple mobile device usb driver ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии