503 ошибка tomcat

I hosted my application, and doing some stress tests, I noticed that when shooting around 50 requests in parallel, the server responds HTTP 503.

What does this means? It may be some specific configuration limiting the number of requests from Tomcat?

Thanks.

asked Jan 11, 2012 at 19:43

Rafael Orágio's user avatar

Rafael OrágioRafael Orágio

1,7085 gold badges19 silver badges26 bronze badges

2

That typically just means you’ve run out of threads to handle the request. You could try increasing the maxThreads in your Tomcat server.xml file, or if you’re using Apache HTTP server as a front end, you may need to configure your Connector to allow more connections.

answered Jan 13, 2012 at 5:01

jbindel's user avatar

A 503 status indicates the service handling the request is unavailable.

The server is currently unable to handle the request due to a
temporary overloading or maintenance of the server.

— HTTP Specification on 503

From time-to-time you’ll see this if you’re running Tomcat behind Apache, with Apache operating as a proxy. If Apache is unable to contact Tomcat it will return a 503 response.

Community's user avatar

answered Jan 12, 2012 at 10:49

johnstok's user avatar

johnstokjohnstok

95.7k12 gold badges54 silver badges76 bronze badges

If you are using Apache httpd as a front-end, you may want to check if there is a firewall between Tomcat and Apache. After having disabled the firewall on the Tomcat machine in our environment, the 503 errors disappeared.

See also this.

Above document also describes other less drastic ways of solving the 503 problem when a firewall is involved.

rjdkolb's user avatar

rjdkolb

10.3k11 gold badges69 silver badges88 bronze badges

answered Feb 27, 2014 at 11:00

botkop's user avatar

botkopbotkop

9241 gold badge8 silver badges17 bronze badges

0

the server was running fine the last few months then suddenly today and yesterday it just stop responding and returned the 503 error. it works when i restarted the server but in a few hours, it stops again and returns the 503 error. The problem is i don’t know what causes the problem time to time. i checked the error log and the file size is too large; could this be the problem of the sudden error on the tomcat server?

Any Help Will do

asked Apr 13, 2011 at 1:14

user705099's user avatar

1

Best to tail the log files, when the error occurs and debug from there. If the log files are too large, zero them out, make a backup of it, and restart Tomcat and try.

answered Oct 13, 2012 at 1:57

unixrules's user avatar

unixrulesunixrules

6084 silver badges7 bronze badges

Solution 1

That typically just means you’ve run out of threads to handle the request. You could try increasing the maxThreads in your Tomcat server.xml file, or if you’re using Apache HTTP server as a front end, you may need to configure your Connector to allow more connections.

Solution 2

A 503 status indicates the service handling the request is unavailable.

The server is currently unable to handle the request due to a
temporary overloading or maintenance of the server.

— HTTP Specification on 503

From time-to-time you’ll see this if you’re running Tomcat behind Apache, with Apache operating as a proxy. If Apache is unable to contact Tomcat it will return a 503 response.

Related videos on Youtube

Apache Tomcat HTTP status 404 error

03 : 08

Apache Tomcat HTTP status 404 error

How to Solve HTTP 503 Error Easiest Method [ WITH PROOF ]

05 : 19

How to Solve HTTP 503 Error Easiest Method [ WITH PROOF ]

How to Resolve Http Error 503 Service Unavailbale

02 : 21

How to Resolve Http Error 503 Service Unavailbale

How to Fix the HTTP Error 503 for WordPress Sites

03 : 00

How to Fix the HTTP Error 503 for WordPress Sites

HTTP Status Code 503: What Is a 503 Error "Service Unavailable" Response Code?

04 : 28

HTTP Status Code 503: What Is a 503 Error «Service Unavailable» Response Code?

Tomcat Port Problem

02 : 57

AWS KC Videos: How do I troubleshoot HTTP 503 errors returned when using a Classic Load Balancer?

09 : 39

AWS KC Videos: How do I troubleshoot HTTP 503 errors returned when using a Classic Load Balancer?

03 [503 service unavailable] Oracle Apex 5.1 Tutorial [ARABIC]

13 : 57

03 [503 service unavailable] Oracle Apex 5.1 Tutorial [ARABIC]

How to Fix 503 Server Unavailable on your Website

07 : 26

How to Fix 503 Server Unavailable on your Website

HTTP Error 503  The service is unavailable

02 : 20

HTTP Error 503 The service is unavailable

Comments

  • I hosted my application, and doing some stress tests, I noticed that when shooting around 50 requests in parallel, the server responds HTTP 503.

    What does this means? It may be some specific configuration limiting the number of requests from Tomcat?

    Thanks.

Recents

Related

последовательность

В этой статье в основном описаны ошибки 502, 504 и 503 nginx и tomcat и их общие причины.

502

определение

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

Общая причина

  • Если серверная служба не работает, 502 напрямую
  • Серверная служба перезапускается

Пример

Отключите внутреннюю службу, а затем отправьте запрос внутреннего интерфейса в nginx, журнал будет следующим:

  • access.log
127.0.0.1 - - [22/Dec/2017:20:44:38 +0800] "GET /timeout/long-write HTTP/1.1" 502 537 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36"
Скопировать код
  • error.log
2017/12/22 20:45:12 [error] 1481#0: *3 kevent() reported that connect() failed (61: Connection refused) while connecting to upstream, client: 127.0.0.1, server: localhost, request: "GET /timeout/long-write HTTP/1.1", upstream: "http://[::1]:8080/timeout//long-write", host: "localhost:8888"
Скопировать код

504

определение

504 Тайм-аут шлюза: когда сервер, работающий в качестве шлюза или прокси-сервера, пытался выполнить запрос, он не смог вовремя получить ответ от вышестоящего сервера (сервера, идентифицированного URI, например HTTP, FTP, LDAP) или вторичного сервера (например, DNS). Примечание. Некоторые прокси-серверы возвращают ошибку 400 или 500, когда истекает время ожидания DNS-запроса.

Общая причина

  • Этот интерфейс занимает слишком много времени, серверная служба получает запрос, начинает выполнение и не может вернуть данные в nginx в заданное время.
  • Общая нагрузка на внутренний сервер слишком высока. После получения запроса из-за загруженного потока запрошенный интерфейс не может быть организован, в результате чего не удается вернуть данные в nginx в установленное время.

Пример

  • Возврат переднего конца
<html>
<head><title>504 Gateway Time-out</title></head>
<body bgcolor="white">
<center><h1>504 Gateway Time-out</h1></center>
<hr><center>openresty/1.9.15.1</center>
</body>
</html>
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
Скопировать код
  • access.log
192.168.99.1 - - [22/Dec/2017:21:58:20 +0800] "GET /timeout/long-resp HTTP/1.1" 504 591 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "-" "-"
Скопировать код
  • error.log
2017/12/22 21:58:20 [error] 5#5: *7 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 192.168.99.1, server: , request: "GET /timeout/long-resp HTTP/1.1", upstream: "http://192.168.99.100:8080/timeout//long-resp", host: "192.168.99.100:8686"
Скопировать код
  • nginx.conf
        location /timeout/long-resp {
            proxy_connect_timeout    30;
            proxy_read_timeout       100;
            proxy_send_timeout       10;
            proxy_pass http://192.168.99.100:8080/timeout/long-resp ;
        }
Скопировать код
  • код Java
    @GetMapping("/timeout/long-resp")
    public String longResp() throws InterruptedException {
        TimeUnit.SECONDS.sleep(120);
        return "finish";
    }
Скопировать код

Сервер принял запрос и не вернулся, nginx сообщил, что соединение истекло после ожидания в течение 100 секунд, и вернул 504; но бэкэнд продолжал выполняться, и выполнение было завершено на 120-й секунде.

503(Относительно редкий)

определение

503 Служба недоступна: указывает, что сервер в настоящее время находится в временно недоступном состоянии, будь то намеренное или непреднамеренное, когда сервер находится в недоступном состоянии, этот код состояния будет возвращен. Среди них услуга остановки сервера из-за необходимости обслуживания является преднамеренной ситуацией. Когда сам сервер перегружен и не отвечает, это непреднамеренно. Кроме того, серверы в этих местах, такие как балансировщики нагрузки или интерфейсные машины веб-серверов, также могут возвращать 503.

Общая причина

  • Nginx ограничивает ток и возвращает 503, если скорость превышает лимит.
  • Регулярное обслуживание серверных служб, таких как пауза tomcat

Текущий лимит Nginx возвращает 503 экземпляра

  • config
http{
    ## test 503
    limit_conn_zone $binary_remote_addr zone=addr:10m;
    server {
        listen 8686;
        location /timeout {
            limit_conn addr 1;
            proxy_connect_timeout    30;
            proxy_read_timeout       100;
            proxy_send_timeout       2;
            proxy_pass http://192.168.99.100:8080/timeout/ ;
        }
    }
}
Скопировать код
  • error.log
2017/12/24 20:58:29 [error] 5#5: *1473 limiting connections by zone "addr", client: 192.168.99.1, server: , request: "GET /timeout/busy HTTP/1.1", host: "192.168.99.100:8686"
Скопировать код
  • access.log
192.168.99.1 - - [24/Dec/2017:20:58:39 +0800] "GET /timeout/busy HTTP/1.1" 503 219 "-" "-" "-" "-"
Скопировать код
  • client
wrk -t12 -c200 -d100s -T60s  --latency http://192.168.99.100:8686/timeout/busy
➜  ~ curl -i http://192.168.99.100:8686/timeout/busy
HTTP/1.1 503 Service Temporarily Unavailable
Server: openresty/1.9.15.1
Date: Sun, 24 Dec 2017 12:58:26 GMT
Content-Type: text/html
Content-Length: 219
Connection: keep-alive
<html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body bgcolor="white">
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>openresty/1.9.15.1</center>
</body>
</html>
Скопировать код

tomcat возвращает 503 экземпляра

  • Http11Processor tomcat-embed-core-8.5.23-sources.jar!/org/apache/coyote/http11/Http11Processor.java
	@Override
    public SocketState service(SocketWrapperBase<?> socketWrapper)
        throws IOException {
        RequestInfo rp = request.getRequestProcessor();
        rp.setStage(org.apache.coyote.Constants.STAGE_PARSE);

        // Setting up the I/O
        setSocketWrapper(socketWrapper);
        inputBuffer.init(socketWrapper);
        outputBuffer.init(socketWrapper);

        // Flags
        keepAlive = true;
        openSocket = false;
        readComplete = true;
        boolean keptAlive = false;
        SendfileState sendfileState = SendfileState.DONE;

        while (!getErrorState().isError() && keepAlive && !isAsync() && upgradeToken == null &&
                sendfileState == SendfileState.DONE && !endpoint.isPaused()) {
                //......

                if (endpoint.isPaused()) {
                    // 503 - Service unavailable
                    response.setStatus(503);
                    setErrorState(ErrorState.CLOSE_CLEAN, null);
                } else {
                    keptAlive = true;
                    // Set this every time in case limit has been changed via JMX
                    request.getMimeHeaders().setLimit(endpoint.getMaxHeaderCount());
                    if (!inputBuffer.parseHeaders()) {
                        // We've read part of the request, don't recycle it
                        // instead associate it with the socket
                        openSocket = true;
                        readComplete = false;
                        break;
                    }
                    if (!disableUploadTimeout) {
                        socketWrapper.setReadTimeout(connectionUploadTimeout);
                    }
                }

        }    
    }        
Скопировать код

Пока состояние конечной точки приостановлено, вернуть 503

  • AbstractEndpoint tomcat-embed-core-8.5.23-sources.jar!/org/apache/tomcat/util/net/AbstractEndpoint.java
	/**
     * Pause the endpoint, which will stop it accepting new connections.
     */
    public void pause() {
        if (running && !paused) {
            paused = true;
            unlockAccept();
            getHandler().pause();
        }
    }

    /**
     * Resume the endpoint, which will make it start accepting new connections
     * again.
     */
    public void resume() {
        if (running) {
            paused = false;
        }
    }
Скопировать код

Вот методы паузы и возобновления конечной точки

  • запрос

Когда запрос вводит служебный метод Http11Processor для выполнения метода endpoint.isPaused (), tomcat приостанавливается. В это время будет возвращено 503, как показано ниже:

➜  ~ curl -i http://localhost:8080/demo/test
HTTP/1.1 503
Transfer-Encoding: chunked
Date: Sun, 24 Dec 2017 14:10:16 GMT
Connection: close
Скопировать код

резюме

  • 502 Обычно серверная служба не работает или перезапускается
  • 504 Выполнение запрошенного интерфейса обычно занимает много времени, или нагрузка на внутреннюю службу высока и требует много времени для выполнения
  • 503 Обычно ограничение по току nginx или пауза в обслуживании серверной части для обслуживания

doc

  • Сводка кода состояния Nginx
  • Анализ ошибок nginx 502, 503, 504
  • Сводка условий и способов устранения ошибки Nginx 502 503


posted 6 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

You can use the command «netstat -tnlp» to list what programs are listing on which ports/protocols.

But it does appear that Apache is attempting to use IPv6 to communicate and your listening address on the connector is set for IPv4.

Unfortunately, Apache does its IPv6/IPv4 things with a certain amount of «magic» these days, so it’s not always easy to tell what protocols it’s going to use. You’ll probably have to read the Apache docs. I would expect that the mod_jk configuration options would deal with that, but unfortunately, the DigitalOcean tutorial doesn’t show a functional and complete set of sample mod_jk directives  

It’s not totally essential that you limit the port 8009 listening address. That’s not a public port, so access to it should be firewall-blocked both at the external entry to your site from the Internet, and in your case, on the local machine (iptables) itself. If someone managed to get far enough into your server to be able to send local requests inside the machine’s firewall, you’ve probably already be totally eaten.

Also, are you the «Bostich» that posted to the DigitalOcean site not long ago? We really would like to be notified when you cross-post stuff. Otherwise people get confused because sometime they’ll answer on one site and sometimes on another.

The secret of how to be miserable is to constantly expect things are going to happen the way that they are «supposed» to happen.

You can have faith, which carries the understanding that you may be disappointed. Then there’s being a willfully-blind idiot, which virtually guarantees it.

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

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

  • Яндекс еда ошибка привязки карты
  • 503 ошибка get
  • 503 ошибка beget
  • 503 код ошибки http
  • 502в код ошибки что значит

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

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