Ah01102 error reading status line from remote server localhost

how to fix apache2 "proxy_http:error" AH01102: error reading status line from remote server localhost:4382. I have an apache2 webserver which is being used to serve few nodejs applications in the

how to fix apache2 «proxy_http:error» AH01102: error reading status line from remote server localhost:4382.

I have an apache2 webserver which is being used to serve few nodejs applications in the backend.

Apache2 webserver version:
Server version: Apache/2.4.41 (Ubuntu)
Server built: 2019-08-21T20:43:05

Nodejs version: v10.18.1

Mongo db version: v4.0.15

We have been plague by this below error/errors(see logs) on all our backend applications
«proxy_http:error» AH01102: error reading status line from remote server localhost:4382.

[Mon Apr 27 20:09:05.697271 2020] [proxy_http:error] [pid 26792:tid 140063099688704] (70007)The timeout specified has expired: [client 178.153.198.97:52385] AH01095: prefetch request body failed to 127.0.0.1:4381 (localhost) from 178.153.198.97 (), referer: https://www.example.com/sub-admin/menus/add-menu
[Mon Apr 27 20:21:51.617095 2020] [proxy_http:error] [pid 26764:tid 140062901626624] (104)Connection reset by peer: [client 178.153.195.206:61268] AH01102: error reading status line from remote server localhost:4382, referer: http://www.example.com/restaurant/dashboard
[Mon Apr 27 20:21:51.617117 2020] [proxy:error] [pid 26764:tid 140062901626624] [client 178.153.195.206:61268] AH00898: Error reading from remote server returned by /restaurant/assets/img/avatars/5.jpg, referer: http://www.example.com/restaurant/dashboard
[Tue Apr 28 03:51:28.498423 2020] [proxy_http:error] [pid 26793:tid 140062868055808] (104)Connection reset by peer: [client 89.211.117.185:57622] AH01102: error reading status line from remote server localhost:4382, referer: http://www.example.com/restaurant/dashboard
[Tue Apr 28 03:51:28.498455 2020] [proxy:error] [pid 26793:tid 140062868055808] [client 89.211.117.185:57622] AH00898: Error reading from remote server returned by /restaurant/static/css/main.f8d32764.chunk.css, referer: http://www.example.com/restaurant/dashboard


So far i have tried these things to fix this error.

  1. ProxyPreserveHost On — It didn’t workout.

  2. disablereuse=on. It didn’t work.

  3. Timeout=600, then Timeout=900. Didn’t work.

  4. retry=1 acquire=3000 timeout=600 Keepalive=On. Didn’t work.

  5. SetEnv force-proxy-request-1.0 1
    SetEnv proxy-nokeepalive 1

Worked for small duration(12 hours). Again same error got reproduce with pretty much
same frequency as earlier.

  1. SetEnv proxy-initial-not-pooled 1
    SetEnv proxy-nokeepalive 1

This one worked for 24 hours. Then after 24 hours, this error got reproduce. Though this time after 24 hours, error is occurring only once in an hour, sometimes only
once in two hours, sometime once in two-five hours.

1Q. First of all why this error happening.

2Q. Is this error occurring only because of apache or nodejs application can also be culprit
(But there’s hardly any error logs of the application, when this apache error occurs).

3Q. How/What is the best way to identify, diagnosis and resolve this error, coz after searching
on various forums, no one seems to have resolve this error it perfectly or have a right
answer for it and this has been the case since 2006, looking at some of the forums.

Here is my apache config file

<VirtualHost *:443>
  ServerAdmin root@example.com
  ServerName  www.example.com
  ServerAlias example.com

  SSLEngine On
  SSLProxyEngine On
  SSLCertificateFile "/etc/ssl/private/server.crt"
  SSLCertificateKeyFile "/etc/ssl/private/server.key"


  ProxyRequests Off

    #Admin
    ProxyPass /admin http://localhost:4380/
    ProxyPassReverse /admin http://localhost:4380/
    SetEnv proxy-nokeepalive 1
    SetEnv proxy-initial-not-pooled 1


    ProxyPass /restaurant http://localhost:4382/
    ProxyPassReverse /restaurant http://localhost:4382/
    SetEnv proxy-nokeepalive 1
    SetEnv proxy-initial-not-pooled 1


    ProxyPass /sub-admin http://localhost:4385/
    ProxyPassReverse /sub-admin http://localhost:4385/
    SetEnv proxy-nokeepalive 1
    SetEnv proxy-initial-not-pooled 1


    #API
    ProxyPass /admin-api/ http://localhost:4381/
    ProxyPassReverse /admin-api/ http://localhost:4381/
    SetEnv proxy-nokeepalive 1
    SetEnv proxy-initial-not-pooled 1


    ProxyPass /restaurant-api/ http://localhost:4379/
    ProxyPassReverse /restaurant-api/ http://localhost:4379/
    SetEnv proxy-nokeepalive 1
    SetEnv proxy-initial-not-pooled 1


</VirtualHost>


I have two apache servers setup on two separate physical machines. My current setup is:

                      Apache 1 (Reverse Proxy) <===> Apache 2

Both apache server versions are Apache/2.4.29 (Ubuntu) running on Ubuntu 18.04.4 LTS and their /etc/apache2/apache.conf files are identical.

Apache 1 sites-enabled config:

<VirtualHost *:80>
        ServerName subdomain.domain.tld
        ServerAlias www.subdomain.domain.tld

        ServerAdmin webmaster@domain.tld
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        <Proxy *>
                Order deny,allow
                Allow from all
        </Proxy>

        ProxyRequests off
        ProxyPreserveHost On
        ProxyPass /maintenance_page !
        ProxyPass / http://[apache2-ip-address]:27300/ 
        ProxyPassReverse / http://[apache2-ip-address]:27300/
</VirtualHost>

Apache 2 sites-enabled config:

<VirtualHost *:27300>
        ServerName subdomain.domain.tld
        ServerAlias www.subdomain.domain.tld

        ServerAdmin webmaster@domain.tld
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        ErrorDocument 400 /notfound.html

        ProxyRequests off
        ProxyPreserveHost on
</VirtualHost>

If I directly hit http://[apache2-ip-address]:27300/ from the web browser the apache server landing page comes up fine. If I enter http://subdomain.domain.tld into the browser I get a proxy error:

The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request

I logged a trace on both apache servers. Apache server 2 is receiving the proxied request from apache server 1 and is returning a 200 status response perfectly fine to apache server 1. The flow breaks at apache server 1 where I am seeing the following logs:

[Sat Jul 11 20:34:08.671267 2020] [proxy:debug] [pid 32275:tid 140388069250816] proxy_util.c(3075): AH00962: HTTP: connection complete to [apache2-ip-address]:27300 ([apache2-ip-address])
[Sat Jul 11 20:34:08.671333 2020] [core:trace6] [pid 32275:tid 140388069250816] core_filters.c(525): [remote [apache2-ip-address]:27300] core_output_filter: flushing because of FLUSH bucket
[Sat Jul 11 20:34:08.677508 2020] [proxy_http:error] [pid 32275:tid 140388069250816] (104)Connection reset by peer: [client xx.xxx.xxx.xx:39014] AH01102: error reading status line from remote server [apache2-ip-address]:27300
[Sat Jul 11 20:34:08.677575 2020] [proxy_http:debug] [pid 32275:tid 140388069250816] mod_proxy_http.c(1324): [client xx.xxx.xxx.xx:39014] AH01105: NOT Closing connection to client although reading from backend server [apache2-ip-address]:27300 failed.
[Sat Jul 11 20:34:08.677624 2020] [proxy:error] [pid 32275:tid 140388069250816] [client xx.xxx.xxx.xx:39014] AH00898: Error reading from remote server returned by /
[Sat Jul 11 20:34:08.677681 2020] [proxy:debug] [pid 32275:tid 140388069250816] proxy_util.c(2192): AH00943: HTTP: has released connection for ([apache2-ip-address])
[Sat Jul 11 20:34:08.677724 2020] [http:trace3] [pid 32275:tid 140388069250816] http_filters.c(1128): [client xx.xxx.xxx.xx:39014] Response sent with status 502, headers:

Things I’ve tried, from few other discussions I could find online, are the following changes to apache server 1 sites-enabled config :

  1. SetEnv proxy-initial-not-pooled 1
  2. SetEnv force-proxy-request-1.0 1
  3. SetEnv proxy-nokeepalive 1
  4. ProxyTimeout 600
  5. ProxyPass / http://[apache2-ip-address]:27300/ timeout=600
  6. ProxyPass / http://[apache2-ip-address]:27300/ nocanon

I’ve pretty much bruteforced the situation with several combinations of the above settings, but nothing seems to work. Any help is appreciated.

An additional check I ran is, if I run a nodejs application or python flask service on the same machine as either apache servers and proxy the service using ProxyPass / http://localhost:[port]/, the setup works properly. So both apache servers are running fine and are able to proxy services on their respective localhosts. Whatever is breaking has to do with the communication between the two apache servers.

UPDATE : Upon further triaging using curl with a networking person, the issue seems to be that the org firewall is only allowing inbound traffic to apache server 2 and blocking outbound traffic which may be causing 502 errors on apache server 1. This didn’t seem like the issue up until I realized that my laptop was VPN’ed into the org network all along while testing and apache server 1 is sitting outside the org network. If this turns out to be the issue it’s going to be a real bummer.

Содержание

  1. Ошибка прокси-сервера Apache2: ошибка чтения с удаленного сервера
  2. Ошибка прокси-сервера Apache2: Ошибка чтения с удаленного сервера
  3. Ah01102 error reading status line from remote server
  4. Unable to login, Proxy Error — Error reading from remote server
  5. Proxy Error
  6. apache2 proxy recursion
  7. Apache reverse proxy? #378
  8. Comments
  9. gerroon commented Jan 24, 2019 •
  10. pcause commented Jan 24, 2019
  11. gerroon commented Jan 24, 2019
  12. zadam commented Jan 24, 2019
  13. pcause commented Jan 24, 2019
  14. zadam commented Jan 24, 2019
  15. gerroon commented Jan 24, 2019
  16. zadam commented Jan 24, 2019 •
  17. gerroon commented Jan 24, 2019
  18. gerroon commented Jan 24, 2019 •
  19. pcause commented Jan 26, 2019
  20. gerroon commented Mar 6, 2019
  21. truejelly commented Sep 25, 2019
  22. MetroWind commented Nov 22, 2019 •
  23. App behind mod_proxy is only partially reachable #14
  24. Comments
  25. jfmcbrayer commented Apr 17, 2015
  26. icing commented Apr 21, 2015
  27. Ошибка прокси 502 «Причина: ошибка чтения с удаленного сервера» с Apache 2.2.3 (Debian) mod_proxy и Jetty 6.1.18

Ошибка прокси-сервера Apache2: ошибка чтения с удаленного сервера

Сам сайт работает и работает нормально, я добавил много записей в базу данных, которую веб-сервер nanohttpd возвращает на некоторых конечных точках.

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

Я уже немного осмотрелся и думаю, что это может быть проблема с тайм-аутом, но я добавил тайм-ауты на свой виртуальный хост, и эта проблема все еще сохраняется.

Мой текущий файл VirtualHost для этого:

Раньше я пробовал добавлять timeout=x и connectiontimeout=x за ProxyPass, но это, похоже, не помогло.

Редактировать: Поскольку ответа до сих пор нет, вот еще немного информации, я добавлю награду, как только получу право.

Как вы можете видеть в моем файле VirtualHost, я использую обратный прокси-сервер Apache, чтобы включить SSL для своего приложения.

Итак, мой маленький сервер nanohttpd в основном возвращает очень упрощенную html-страницу с таблицей и строкой для каждой записи базы данных. Если в конкретной категории более 100 записей, я получу сообщение об ошибке прокси-сервера.

На данный момент я совершенно уверен, что это связано с каким-то тайм-аутом, но я просмотрел так много сообщений и пытался добавить конфиги в свои, и (да, я перезапускал Apache2 после каждого изменения) пока ничего не работало.

Может ли это быть что-то на моем сервере nanohttpd, чего мне не хватает? Простой заголовок или файл cookie, на данный момент я не отправляю ни одного из них.

Если какая-либо необходимая информация отсутствует, пожалуйста, сообщите мне.

Источник

Ошибка прокси-сервера Apache2: Ошибка чтения с удаленного сервера

Сам сайт работает и работал нормально, я добавил в базу данных много записей, которые веб-сервер nanohttpd возвращает на некоторых конечных точках

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

Я уже немного осмотрелся и думаю, что это может быть проблема тайм-аута, но я добавил тайм-ауты на свой виртуальный хост, и эта проблема все еще сохраняется

Мой текущий файл VirtualHost для этого:

Ранее я пытался добавить timeout = x и connectiontimeout = x за ProxyPass, но это, похоже, не помогло

Изменить: так как ответа пока нет, есть дополнительная информация, я добавлю вознаграждение, как только получу право.

Как вы можете видеть в моем файле VirtualHost, я использую обратный прокси-сервер Apache, чтобы включить SSL для моего приложения.

Так что мой маленький сервер nanohttpd в основном возвращает очень упрощенную HTML-страницу с таблицей и строкой для каждой записи базы данных. Если в конкретной категории более 100 записей, я получу сообщение об ошибке прокси.

На данный момент я совершенно уверен, что это связано с тайм-аутом, но я просмотрел так много постов и попытался добавить конфиги к своему и (да, я перезапускал Apache2 после каждого изменения), пока ничего не получалось.

Может ли быть что-то на моем сервере nanohttpd, что я пропускаю? Простой Заголовок или Cookie, я не отправляю ни одного из них на данный момент.

Если какая-либо необходимая информация отсутствует, пожалуйста, дайте мне знать.

Источник

Ah01102 error reading status line from remote server

Unable to login, Proxy Error — Error reading from remote server

Since this morning, without any change on the server and any change on the confluence app, I cannot loggin to the app.

confluence version: 5.3.1

I use Apache/2.4.7 with mod_proxy

I restart both confluence and apache without success.

Confluence is running, the disk is not full.

Each attempt result to the following http error:

Proxy Error

The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request POST /confluence/dologin.action .

Reason: Error reading from remote server

On apache server log i found the following logs:

[Wed Feb 27 16:56:10.546387 2019] [proxy_http:error] [pid 3833] (70007)The timeout specified has expired: [client 193.248.40.185:59926] AH01102: error reading status line from remote server localhost:8090, referer: http://xxx/confluence/dologin.action
[Wed Feb 27 16:56:10.546451 2019] [proxy:error] [pid 3833] [client 193.248.40.185:59926] AH00898: Error reading from remote server returned by /confluence/dologin.action, referer: http://xxx/confluence/dologin.action
[Wed Feb 27 16:56:10.556796 2019] [proxy_http:error] [pid 1107] (70007)The timeout specified has expired: [client 193.248.40.185:59684] AH01102: error reading status line from remote server localhost:8090, referer: http://xxx/confluence/dologin.action
[Wed Feb 27 16:56:10.556843 2019] [proxy:error] [pid 1107] [client 193.248.40.185:59684] AH00898: Error reading from remote server returned by /confluence/dologin.action, referer: http://xxx/confluence/dologin.action

I tried to update the ProxyTimeout without success.

I don’t know where to search since I did not found any related issue.

apache2 proxy recursion

После установки веб-приложение создало конфиг apache и стало доступно по http://0.0.0.0/egroupware

Требуется сделать приложение доступным по DNS, причем приведенный конфиг нельзя править.

На такое в логеapache2/errror.log возмущение:

Погоди. Твой nginx слушает *:80 и выполняет проксирование на localhost:80 ? Ничего не смущает?

Где-то здесь и появился адский редирект. Возможно из-за того, что proxy_pass прямо в server, без location

И в логе apache какой-то прокси упомянут, хотя в конфиге его не вижу

Разнеси nginx и apache по разным портам, будет гораздо легче

Если это невозможно — по разным хостам

Ну в крайнем случае nginx на нестандартный порт и через iptables — редирект _внешних_ обращений на nginx

Потом уже можно будет смотреть в дампе, кто именно возвращает редиректы и дебажить

Где-то здесь и появился адский редирект. Возможно из-за того, что proxy_pass прямо в server, без location

приходит на nginx запрос

Он его проксирует на

, попадает на тот же самый nginx на _дефолтный_ сайт, и снова проксирует на

Где тут вклинился апач я не вижу, но редирект именно из-за того, что на nginx редирект на тот же самый nginx

попадает на тот же самый nginx на _дефолтный_ сайт, и снова проксирует на

Ну в крайнем случае nginx на нестандартный порт и через iptables — редирект _внешних_ обращений на nginx

Воот, это должно сработать.

Про nginx это меня переклинило, у тебя же один апач

Apache reverse proxy? #378

How can I run the docker install behind Apache reverse proxy?

I tried this line below under Apache and it does not work (Docker port is 8000 btw for me)

It works fine inside my network but I want to access it from outside

it redirects to /login

The text was updated successfully, but these errors were encountered:

Know they are different, but I am using ngix and this is what I have in my config file:

maybe something here gives you a hint at other directives you might need.

Thanks but I do not use nginx and I am not seeing anything in your lines that can be helpful with apache.

I’ve never tried Trilium with Apache, but there shouldn’t be any special setup required, just standard reverse proxy config.

@zadam perhaps when @gerroon posts what he did to get it working you could add a wiki page that has the nginx and apache config data.

Good idea, for now I added your config to https://github.com/zadam/trilium/wiki/Server-installation (I hope it’s ok for you)

See my first post, I have what I put in my apache config.

Entering URL/trilium redirects to URL/login so it breaks the url structure

Trilium redirect and all referencing is done with relative paths so proxy forwarding needs to be done to «trilium/» (notice slash at the end)

yeah it does not work

This kind of works , I can get to login screen but afterwords I get an error

Just after pressing login

thanks for the wiki update. hope it helps others.

I am still not getting any success with this 🙁 If anyone has any updated info on this, that would be great

I have also experienced some problems with running Trilium in docker behind Apache reverse proxy. Using config provided on wiki Apache-proxy-setup allows me to access my instance just fine, I can not however change note’s original type. Doing so gives me an error:
Error when calling PUT notes/xu9IvQFyCa1q/type/code/mime/text%2Fx-c%2B%2Bsrc: 404 — Not Found
After that, the note still behaves as if it was of the original type. That is changing note type from text to C++ does not result in the proper highlighting of c++ syntax. This issue does not occur on local network which leads me to believe that the problem is with my apache config. I’m running Apache 2.4.6 on CentOS 7.6.1810 Below are some more details:

Apache error log:

browser developer log:

Any help would be appreciated

My apache config is

Trilium server was running on port 8181. However after I got to the setup page, clicking “Finish setup” didn’t work. Looking at the HTTP requests in the browser dev tool, it’s this problem.

App behind mod_proxy is only partially reachable #14

This is, unfortunately, another vague-ish bug report.

I have ownCloud running in a kvm-qemu VM. The host machine is running my main apache server, to which I’ve just added mod_h2. The VM’s apache is proxied like this:

Most of the resources load, but for a few, I am getting a 502 Bad Gateway error.

The errors in the ssl_errors.log on the host machine look like

There are no errors in the error_log on the guest machine (the one behind the proxy), and the access_log on the guest machine is showing either 200 or 304 results for all of those requests.

After disabling mod_h2, things work normally.

Again, I’m sorry if this bug report is not very helpful. I think mod_h2 is a great thing and I’m really looking forward to being able to use it.

The text was updated successfully, but these errors were encountered:

Thanks for the update. Yes, that would make sense.

In the meantime I installed rainloop and did some rework of the header conversions and input handling. The initial login problems appear for me now sometimes, most of the times the admin login works. It looks ok from my side, but I do not know what to expect of rainloop. If you could give the current github master a try and report your experience, that’d be nice.

If you continue to have problems, could reproduce this with
LogLevel h2:trace1
and send the the error log? Thanks!

This appears to be fixed as of 6b44c55, probably thanks to the Host header fixes. It’s still not possible to log in to this ownCloud site, but that’s probably the same issue as #13.


Reply to this email directly or view it on GitHub.

bytes GmbH
Hafenweg 16, 48155 Münster, Germany
Phone: +49 251 2807760. Amtsgericht Münster: HRB5782

Ошибка прокси 502 «Причина: ошибка чтения с удаленного сервера» с Apache 2.2.3 (Debian) mod_proxy и Jetty 6.1.18

Apache получает запросы через порт 80 и передает их в Jetty через порт 8080

Моя дилемма: все работает нормально (быстрые запросы, несколько секунд или несколько десятков секунд, запросы обрабатываются нормально ). Проблемы возникают, когда обработка запроса занимает много времени (несколько минут?).

Если я вместо этого выдаю запрос непосредственно в Jetty через порт: 8080, запрос обрабатывается ОК. Так что проблема, скорее всего, находится где-то между Apache и Jetty, где я использую mod_proxy . Как это решить?

Я уже попробовал некоторые «хитрости», связанные с настройками KeepAlive, но без удачи. Вот моя текущая конфигурация, есть предложения?

Вот также журнал отладки из ошибочного запроса:

Я решил проблему. Keepalive=On Должен быть вставлен в ProxyPass конфигурации линии:

там? Это критично;)

Вы пробовали установку setenv proxy-initial-not-pooled 1 ?

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

Глядя на журнал, есть время ожидания 5 минут (= 300 секунд). Это довольно долго ждать ответа. Когда вы обращаетесь к серверу Jetty напрямую, действительно ли этот ресурс занимает столько времени для получения ответа?

Если пять минут действительно находятся в пределах возможного времени ответа, вы можете попробовать настроить директиву конфигурации ProxyTimeout.

В зависимости от настроек вашей сети, вполне может быть, что нет никакой причины даже пытаться использовать какую-либо систему поддержки активности (существует ли межсетевой экран между сервером приложений и прокси-сервером, который может быть настроен для удаления сеансов, которые простаивают слишком долго?) , но ProxyTimeout повлияет на поведение самого прокси.

Если тот же прокси-сервер также обслуживает другие бэкэнды, было бы лучше сохранить текущий ProxyTimeout и настроить время ожидания в директиве ProxyPass (см. Документацию mod_proxy).

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

Для меня удаление значения заголовка Transfer-Encoding» (binary) в моем приложении-сервере (PHP) решило проблему для:

[proxy_http: ошибка] [pid 17623] (22) Недопустимый аргумент: [клиент 127.0.0.1:44929] AH01102: ошибка чтения строки состояния с удаленного сервера 0.0.0.0:80

Все остальные предложения понравились SetEnv proxy-initial-not-pooled или Keep-Alive не сделали.

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

Например, я обнаружил, что причиной моей проблемы была замена всех экземпляров #LoadModule на LoadModule во всех моих конфигурационных файлах Apache. Так как это решило проблему для меня, поэтому я знал, что моя проблема не была отсутствующим аргументом директивы KeepAlive, а скорее моей проблемой была отсутствующая зависимость.

Потому что, помните, .so файлы — это в основном статические библиотеки. Включение модуля не означает, что он привыкнет, но его отключение означает, что он не может быть использован, и поэтому все, что от него зависит, обязательно потерпит неудачу.

Примечание: этот ответ получил некоторые отрицательные голоса из-за того, что мой первоначальный ответ, казалось, предлагал оставить все модули включенными, навсегда. Хотя теоретически вы можете сделать это, не обязательно что-то сломать, очевидно, что это не лучшее практическое решение.

Поэтому, пожалуйста, поймите, я просто предлагаю это как шаг устранения неполадок, а не окончательное решение.

Также обратите внимание: я использую специальный проект git для отслеживания всех файлов конфигурации apache моей локальной машины. Таким образом, я могу выполнять такие виды глобальных операций поиска и замены в моем рабочем каталоге конфигурации Apache, как этап устранения неполадок. Если включение всех модулей выполнено успешно, попробуйте отключить их снова один за другим и перезапустить apache между ними, пока не найдете нужный модуль, который нужно оставить включенным. Как только вы это выясните, верните репо в исходное состояние и включите только тот модуль, который должен быть включен.

Вы также обнаружите, что использование git для отслеживания ваших конфигурационных файлов apache очищает эти каталоги, так как вам больше не понадобятся эти старомодные файлы .bak и .default.

Источник

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

panovitch opened this issue

Jan 25, 2018

· 22 comments

Comments

@panovitch

Hi there! Was wondering if you have some insight on the following problem:

Long story short

We are running an aiohttp app behind an Apache proxy. Around 20% of requests to the app cause Apache to return 502 Proxy Error.

These happen with requests to all endpoints of the server, and there seems to be no pattern to errors of any kind. The proxy error is returned immediately upon request.
Other servers/apps (built on other frameworks, for example, tornado) run behind the same Apache proxy and do not show the same behavior.

The example of Apache logs:

[Tue Jan 23 12:38:51.050529 2018] [proxy_http:error] [pid <pid>:tid <tid>] (20014)Internal error (specific information not available): [client <IP address>] AH01102: error reading status line from remote server <hostname>

Full error response example:

HTTP/1.1 502 Proxy Error
Connection: Keep-Alive
Content-Length: 502
Content-Type: text/html; charset=iso-8859-1
Date: Tue, 23 Jan 2018 13:47:29 GMT
Keep-Alive: timeout=15, max=100
Server: Apache/2.4.18 (Ubuntu)

502 Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request.
Reason: Error reading from remote server

Your environment

aiohttp==2.3.9
python 3.6.3
Apache 2.4.18

@samuelcolvin

Do you see anything in the logs from aiohttp?

How are you running aiohttp? With gunicorn or directly?

I guess debug level logs from aiohttp (and gunicorn if it’s running) would help.

Also how is the aiohttp server addressed by apache (by an ip or a hostname)? I’ve had similar issues that turned out to be DNS problems which were fixed by using static IPs.

@panovitch

Hi @samuelcolvin,
We are running aiohttp directly.
The Apache addresses the server by a hostname, but I doubt that issue is DNS-related, since other apps also run on the same host and dont have any problems.
There are no records in aiohttp logs for the problematic requests at all.

@asvetlov

@aalhour

Hello @asvetlov,

Do you have any recommendation for us to validate the source of the issue? How can we help you guys resolve this problem?

@asvetlov

@asvetlov

Sorry, after digging in I did not found expected bug.
Cannot reproduce locally.

aiohttp error log is required (with DEBUG level enabled) for getting more information about the problem.

@mariuszluciow

I’m having something similar, running aiohttp behind zuul proxy. After several good responses, and a while of doing nothing, server starts responding with incorrect response, which starts with rnTP/1.1 200 OK instead of HTTP/1.1 200 OK

@asvetlov

  1. Not sure if you have the same problem.
  2. I need reliable way for reproducing the error — otherwise a change for fix is very low. Python test would be awesome.

@panovitch

Hi @asvetlov,

We tried to check the aiohttp debug logs, that’s how we tried to do it, and how we are running the app:

def setup_loggers():
    stream_handler = logging.StreamHandler(stream=sys.stderr) 
    _stream_handler.setLevel(logging.DEBUG)

    loggers = [getLogger('aiohttp.internal'), getLogger('aiohttp.server')]
    for logger in loggers:
        logger.setLevel(logging.DEBUG)
        logger.addHandler(_stream_handler)

def run_app():
    """
    Application runner function.
    """
    setup_loggers()
    app = create_app()
    host = server_option("host")
    port = int(server_option("port"))

    web.run_app(
        app=app, host=host, port=port, access_log=make_logger(is_development=True),
        access_log_format=access_log_format)

We ran the app with this configuration, but were unable to see anything related to the problematic requests — they do not even register in the access log.

I’m posting the Apache config below, hope it might help you reproduce it.

Apache Configuration

apache2.conf

Default config. Nothing special here.

sites-enabled

ServerName mine.localhost.com
ProxyRequests Off

<Location /aiohttp_app/>
ProxyPass http://localhost:8137/ retry=0
ProxyPassReverse http://localhost:8137/
</Location>

Apache Error Logs

[Fri Feb 02 16:05:41.865610 2018] [proxy_http:error] [pid 6146:tid 140638813112064] (20014)Internal error (specific information not available): [client 127.0.0.1:39048] AH01102: error reading status line from remote server localhost:8137
[Fri Feb 02 16:05:41.865899 2018] [proxy:error] [pid 6146:tid 140638813112064] [client 127.0.0.1:39048] AH00898: Error reading from remote server returned by /aiohttp_app/ping
[Fri Feb 02 16:05:41.875609 2018] [proxy_http:error] [pid 6147:tid 140638787933952] (20014)Internal error (specific information not available): [client 127.0.0.1:39050] AH01102: error reading status line from remote server localhost:8137
[Fri Feb 02 16:05:41.875797 2018] [proxy:error] [pid 6147:tid 140638787933952] [client 127.0.0.1:39050] AH00898: Error reading from remote server returned by /aiohttp_app/ping

@asvetlov

Errors are stored in logger named aiohttp.server.
I suggest calling logging.basicConfig(level=logging.DEBUG) to see all logs.

@mariuszluciow

I spend few hours to produce some small replicable example with no luck. If anything changes I will let you know, thanks anyway!

@panovitch

Hi @asvetlov, running the app with logging.basicConfig(level=logging.DEBUG) also doesn’t show anything. To help reproduce the problem, I’ve created this: https://github.com/panovitch/test_aiohttp_502. The repo contains a sample apache config (main config apache.conf, which is not different from the default one AFAIK, and a site config for sites-enabled), a way to test for error, and an app (a copy of the example app really). Please note that error occurs pretty randomly so give the test some time to run.

@panovitch

Hi everyone,

We eventually managed to solve the problem by adding this to our apache proxy config: disablereuse=on -hope this would be useful!

@pfreixes

@panovitch do you have the chance to test if the error is reproducible with Aiohttp 3.x?

Regarding the disablereuse=on you are forcing to open a TCP connection at each time. is this stack running in local or are separated pieces within a network?

@lordmauve

I am seeing this with aiohttp==3.1.3 and Apache 2.4.10.

@rcupic

Hi everyone,

We eventually managed to solve the problem by adding this to our apache proxy config: disablereuse=on -hope this would be useful!

Hello,
Thank you for letting us know your solution. My question is if there is any downgrade in performance with this setup? I have something like 20-30 requests per minute. This setting sounds like disabling pooled connections which means that every of this 20-30 requests will open new connection for itself even if they are from a same client.
@panovitch

@guillaume-fr

Running into similar issue with aiohttp + gunicorn + apache2.
The same service was running fine on another Python stack + apache2.

(32)Broken pipe: [client 192.168.8.1:44745] AH01084: pass request body failed to [::1]:80 (localhost)

In my environment, I’m not allowed to change disablereuse. The admin is suspecting an issue with keep-alive/persistent connections.

@asvetlov

Apache uses multithreaded/multiprocessed workers to process http requests.
What is the point of deployment aiohttp behind this?
The concurrency level is limited by Apache, and the number is small.
In contrast, nginx or haproxy use asynchronous/nonblocking model, they fit with aiohttp pretty well.

Sorry, I’ve not motivated to support aiohttp+apache combination. If somebody wants to provide a pull request — you are welcome.
Since it did not happen for 2 years yet, I’m closing the issue.

@webknjaz

Apache uses multithreaded/multiprocessed workers to process http requests.

FTR this is not entirely true. You can configure it the way nginx works.

@guillaume-fr

I don’t have control over our infrastructure, Apache2 is used as reverse proxy for all our containers. I spent time learning aiohttp, enjoyed it and thanks a lot your work on this project. On my side I think I’ll have to work with another stack.

Maybe add a note in documentation on Apache not being currently supported as a reverse proxy?

@asvetlov

From my understanding, event worker still uses async mode for inactive connections only. Which may work in some scenarios though.
Anyway, this project is volunteer-driven.
If somebody wants to dig into problems with Apache and make a fix — please do.
Docs update that states that Apache usage is discouraged and not fully supported/tested, use it on own risk, is also acceptable.

guillaume-fr

added a commit
to guillaume-fr/aiohttp
that referenced
this issue

Jan 30, 2020

@guillaume-fr

@Humbedooh

Random question, many moons later: what is your transfer-encoding set to?
I discovered a problem where apache would break with a 502 as well, turns out I had transfer-encoding set to chunked with a non-chunked response. Removing that header solved it for me.


Description


Aaron Ogburn



2017-09-04 13:54:46 UTC

Created attachment 35288 [details]
mod_proxy_http patch

For a POST request proxied through mod_proxy_http, it looks like a response timeout is always handled by this block even after 100-continue has been received:

            ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(01102)
                          "error reading status line from remote "
                          "server %s:%d", backend->hostname, backend->port);
            if (APR_STATUS_IS_TIMEUP(rc)) {
                apr_table_setn(r->notes, "proxy_timedout", "1");
                ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01103) "read timeout");
                if (do_100_continue) {
                    return ap_proxyerror(r, HTTP_SERVICE_UNAVAILABLE, "Timeout on 100-Continue");
                }
            }


For instance, logging shows a 100 response is received, but a "Timeout on 100-continue" is still indicated:

[Fri Sep 01 15:59:25.264579 2017] [proxy_http:trace2] [pid 13455:tid 140308050339584] mod_proxy_http.c(1536): [client 127.0.0.1:55835] HTTP: received interim 100 response
[Fri Sep 01 15:59:25.264583 2017] [dumpio:trace7] [pid 13455:tid 140308050339584] mod_dumpio.c(140): [remote 127.0.0.1:8080] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Fri Sep 01 15:59:26.265697 2017] [dumpio:trace7] [pid 13455:tid 140308050339584] mod_dumpio.c(151): [remote 127.0.0.1:8080] mod_dumpio: dumpio_in - 70007
[Fri Sep 01 15:59:26.265753 2017] [proxy_http:error] [pid 13455:tid 140308050339584] (70007)The timeout specified has expired: [client 127.0.0.1:55835] AH01102: error reading status line from remote server 127.0.0.1:8080
[Fri Sep 01 15:59:26.265769 2017] [proxy_http:debug] [pid 13455:tid 140308050339584] mod_proxy_http.c(1264): [client 127.0.0.1:55835] AH01103: read timeout
[Fri Sep 01 15:59:26.265785 2017] [proxy:error] [pid 13455:tid 140308050339584] [client 127.0.0.1:55835] AH00898: Timeout on 100-Continue returned by /app/page


This can result in unwanted worker error states.  Attached is a patch that addressed this on my end.


Comment 2


suv3ndu



2017-11-03 10:18:08 UTC

I found that Apache is “marking down” a JVM once ProxyTimeout elapsed. This is what happens:
 1. A process got kicked off on a JVM. Let’s assume it is going to take lots of time(10 min) to complete.
 2. While this processing is halfway, ProxyTimeout(5 min) elapsed.
 3. Then Apache completely ignores default failontimeout=off setting and marks the JVM down for next 180 Sec(retry value).
 4. Problem started!
 5. Existing users logged on that JVM via that Apache instance

This behavior sounds like bug to me because:
 - If you forcefully failed a HTTP GET request by elapsing ProxyTimeout, Apache 
   *do not* mark the JVM down. It only fails that long running request with 502 
   error. That is expected.
 - If you do the same thing for a HTTP POST request, Apache *mark the
   JVM down*. I am pretty sure, this is *NOT* a desired behavior.

I can easily reproduce the issue with Apache/2.4.10/2.4.25/2.4.28 versions. 

My questions are: 
Is this fix is also going to take care this ProxyTimeout and other different types of timeout scenarios? If yes, from which version this fix will be generally available? If not, please let me know if I can open a separate bug. 


Thanks!
Suvendu

Logs:
[Thu Nov 02 19:25:39.810408 2017] [proxy_http:trace1] [pid 12484:tid 1204] mod_proxy_http.c(1904): [client ::1:59825] HTTP: serving URL http://localhost:8080/second.jsp, referer: http://localhost/
[Thu Nov 02 19:25:39.810408 2017] [proxy:debug] [pid 12484:tid 1204] proxy_util.c(2154): AH00942: HTTP: has acquired connection for (localhost)
[Thu Nov 02 19:25:39.810408 2017] [proxy:debug] [pid 12484:tid 1204] proxy_util.c(2208): [client ::1:59825] AH00944: connecting http://localhost:8080/second.jsp to localhost:8080, referer: http://localhost/
[Thu Nov 02 19:25:39.810408 2017] [proxy:debug] [pid 12484:tid 1204] proxy_util.c(2417): [client ::1:59825] AH00947: connected /second.jsp to localhost:8080, referer: http://localhost/
[Thu Nov 02 19:25:39.811908 2017] [proxy_http:trace3] [pid 12484:tid 1204] mod_proxy_http.c(1375): [client ::1:59825] Status from backend: 100, referer: http://localhost/
[Thu Nov 02 19:25:39.811908 2017] [proxy_http:trace2] [pid 12484:tid 1204] mod_proxy_http.c(1536): [client ::1:59825] HTTP: received interim 100 response, referer: http://localhost/
[Thu Nov 02 19:25:49.812161 2017] [proxy_http:error] [pid 12484:tid 1204] (OS 10060)A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.  : [client ::1:59825] AH01102: error reading status line from remote server localhost:8080, referer: http://localhost/
[Thu Nov 02 19:25:49.812161 2017] [proxy_http:debug] [pid 12484:tid 1204] mod_proxy_http.c(1265): [client ::1:59825] AH01103: read timeout, referer: http://localhost/
[Thu Nov 02 19:25:49.812161 2017] [proxy:error] [pid 12484:tid 1204] [client ::1:59825] AH00898: Timeout on 100-Continue returned by /second.jsp, referer: http://localhost/
[Thu Nov 02 19:25:49.812655 2017] [proxy:debug] [pid 12484:tid 1204] proxy_util.c(2169): AH00943: HTTP: has released connection for (localhost)
[Thu Nov 02 19:25:49.812655 2017] [proxy:debug] [pid 12484:tid 1204] proxy_util.c(1904): AH00933: BALANCER: too soon to retry worker for (localhost)
[Thu Nov 02 19:25:49.812655 2017] [proxy_balancer:debug] [pid 12484:tid 1204] mod_proxy_balancer.c(307): [client ::1:59825] AH01160: Found value DAE82EC9814CC59C66442A5925C32EE7.Tomcat_1 for stickysession JSESSIONID, referer: http://localhost/
[Thu Nov 02 19:25:49.813155 2017] [proxy_balancer:debug] [pid 12484:tid 1204] mod_proxy_balancer.c(320): [client ::1:59825] AH01161: Found route Tomcat_1, referer: http://localhost/
[Thu Nov 02 19:25:49.813155 2017] [proxy:debug] [pid 12484:tid 1204] proxy_util.c(1904): AH00933: BALANCER: too soon to retry worker for (localhost)
[Thu Nov 02 19:25:49.813155 2017] [proxy_balancer:error] [pid 12484:tid 1204] [client ::1:59825] AH01167: balancer://lb-mycluster: All workers are in error state for route (Tomcat_1), referer: http://localhost/


Comment 3


suv3ndu



2017-11-22 09:30:20 UTC

Can someone please let me know when this fix will be GA'ed?


Comment 4


Michael Osipov



2020-01-14 10:29:20 UTC

(In reply to suv3ndu from comment #3)
> Can someone please let me know when this fix will be GA'ed?

I believe this issue is not present in 2.4.x, especially because the patched code block is not present in 2.4.x anymore.

  • Remove From My Forums
  • Question

  • User-1733244450 posted

    can someone help me with this issue? Sometimes i’m getting  Status Code 500/502 and i can’t  find out source of this problem

    .сonf file  -> sites-available

    #<VirtualHost *:*>
    # RequestHeader set «X-Forwarded-Proto» expr=%{REQUEST_SCHEME}
    #</VirtualHost>

    <VirtualHost *:80>
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:5000/ retry=1 acquire=3000 timeout=600 Keepalive=On
    ProxyPassReverse / http://127.0.0.1:5000/
    ServerName www.example.com
    ServerAlias *.example.com
    ErrorLog ${APACHE_LOG_DIR}site-error.log
    # CustomLog ${APACHE_LOG_DIR}site-access.log common
    </VirtualHost>

    <VirtualHost *:443>
    ServerAdmin webmaster@monopoliya.net
    ServerName docs.monopoliya.net
    ErrorLog ${APACHE_LOG_DIR}/error.log
    # CustomLog ${APACHE_LOG_DIR}/access.log combined

    <Proxy *>
    Order deny,allow
    Allow from all
    </Proxy>

    SSLEngine on
    SSLProxyEngine On
    SSLCertificateFile /etc/apache2/ssl/site_net.crt
    SSLCertificateKeyFile /etc/apache2/ssl/site.net.key

    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:5000/ retry=1 acquire=3000 timeout=600 Keepalive=On
    ProxyPassReverse / http://127.0.0.1:5000/
    </VirtualHost>

    service

    [Unit]
    Description=site

    [Service]
    WorkingDirectory=/var/www

    # ExecStart=/usr/share/dotnet/dotnet /var/www/site.dll
    ExecStart=/usr/bin/dotnet /var/www/site.dll
    Restart=always
    # Restart service after 10 seconds if the dotnet service crashes:
    RestartSec=10
    KillSignal=SIGINT
    SyslogIdentifier=site
    User=DotNetUser
    Environment=ASPNETCORE_ENVIRONMENT=Production

    [Install]
    WantedBy=multi-user.target

    [Tue Mar 03 08:37:17.480673 2020] [proxy_http:error] [pid 52938:tid 139622659118848] (20014)Internal error (specific information not available): [client 10.75.5.126:10283] AH01102: error reading status line
    from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
    [Tue Mar 03 08:37:25.082441 2020] [proxy_http:error] [pid 52938:tid 139622139033344] (20014)Internal error (specific information not available): [client 10.75.5.126:10295] AH01102: error reading status line from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
    [Tue Mar 03 09:03:53.558072 2020] [proxy_http:error] [pid 52938:tid 139623095310080] (20014)Internal error (specific information not available): [client 10.75.5.126:1236] AH01102: error reading status line from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
    [Tue Mar 03 09:03:54.906938 2020] [proxy_http:error] [pid 52938:tid 139622675904256] (20014)Internal error (specific information not available): [client 10.75.5.126:1241] AH01102: error reading status line from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
    [Tue Mar 03 09:03:55.017393 2020] [proxy_http:error] [pid 52938:tid 139622642333440] (20014)Internal error (specific information not available): [client 10.75.5.126:1245] AH01102: error reading status line from remote server 127.0.0.1:5000, referer: http://10.75.0.128/
    [Tue Mar 03 09:03:55.017506 2020] [proxy:error] [pid 52938:tid 139622642333440] [client 10.75.5.126:1245] AH00898: Error reading from remote server returned by /User/CheckAccess, referer: http://10.75.0.128/

    and program.cs

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        /*     Host.CreateDefaultBuilder(args)
                 .ConfigureWebHostDefaults(webBuilder => {
                   webBuilder.UseStartup<Startup>();
                 });
                 */
    
          Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => {
              webBuilder.ConfigureKestrel(serverOptions => {
                serverOptions.Limits.MaxConcurrentConnections = 500;
                serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
                serverOptions.Limits.Http2.MaxStreamsPerConnection = 200;
                //serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
                serverOptions.Limits.MinRequestBodyDataRate =
                    new MinDataRate(bytesPerSecond: 100,
                        gracePeriod: TimeSpan.FromMinutes(10));
                serverOptions.Limits.MinResponseDataRate =
                    new MinDataRate(bytesPerSecond: 100,
                        gracePeriod: TimeSpan.FromMinutes(10));
    
                serverOptions.Listen(IPAddress.Loopback, 5000);
                serverOptions.Listen(IPAddress.Loopback, 5001);
                serverOptions.Limits.KeepAliveTimeout =
                    TimeSpan.FromMinutes(300);
                serverOptions.Limits.RequestHeadersTimeout =
                    TimeSpan.FromMinutes(60);
                serverOptions.Limits.KeepAliveTimeout =
                    TimeSpan.FromMinutes(20);
                serverOptions.Limits.RequestHeadersTimeout =
                    TimeSpan.FromMinutes(10);
                serverOptions.Limits.Http2.MaxStreamsPerConnection = 100;
                serverOptions.Limits.Http2.HeaderTableSize = 4096;
    
              })
              .UseStartup<Startup>();
            });
    
        /*Host.CreateDefaultBuilder(args)
            .ConfigureServices((context, services) => {
              services.Configure<KestrelServerOptions>(
                  context.Configuration.GetSection("Kestrel"));
            })
            .ConfigureWebHostDefaults(webBuilder => {
              webBuilder.UseStartup<Startup>();
            });*/
      }

Like this post? Please share to your friends:
  • Ah01071 got error access to the script
  • Ah00558 apache2 ошибка
  • Ah00534 httpd configuration error no mpm loaded
  • Ah00534 apache2 configuration error more than one mpm loaded
  • Ah00526 syntax error on line 27 of etc httpd bx conf default conf