Error reading from remote server returned by

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

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.

Источник

Click here follow the steps to fix Proxy Error Reading From Remote Server Returned By /users/sign_in and related errors.

Instructions

 

To Fix (Proxy Error Reading From Remote Server Returned By /users/sign_in) error you need to
follow the steps below:

Step 1:

 
Download
(Proxy Error Reading From Remote Server Returned By /users/sign_in) Repair Tool
   

Step 2:

 
Click the «Scan» button
   

Step 3:

 
Click ‘Fix All‘ and you’re done!
 

Compatibility:
Windows 7, 8, Vista, XP

Download Size: 6MB
Requirements: 300 MHz Processor, 256 MB Ram, 22 MB HDD

Limitations:
This download is a free evaluation version. To unlock all features and tools, a purchase is required.

Proxy Error Reading From Remote Server Returned By /users/sign_in Error Codes are caused in one way or another by misconfigured system files
in your windows operating system.

If you have Proxy Error Reading From Remote Server Returned By /users/sign_in errors then we strongly recommend that you

Download (Proxy Error Reading From Remote Server Returned By /users/sign_in) Repair Tool.

This article contains information that shows you how to fix
Proxy Error Reading From Remote Server Returned By /users/sign_in
both
(manually) and (automatically) , In addition, this article will help you troubleshoot some common error messages related to Proxy Error Reading From Remote Server Returned By /users/sign_in error code that you may receive.

Note:
This article was updated on 2023-02-03 and previously published under WIKI_Q210794

Contents

  •   1. What is Proxy Error Reading From Remote Server Returned By /users/sign_in error?
  •   2. What causes Proxy Error Reading From Remote Server Returned By /users/sign_in error?
  •   3. How to easily fix Proxy Error Reading From Remote Server Returned By /users/sign_in errors

What is Proxy Error Reading From Remote Server Returned By /users/sign_in error?

The Proxy Error Reading From Remote Server Returned By /users/sign_in error is the Hexadecimal format of the error caused. This is common error code format used by windows and other windows compatible software and driver vendors.

This code is used by the vendor to identify the error caused. This Proxy Error Reading From Remote Server Returned By /users/sign_in error code has a numeric error number and a technical description. In some cases the error may have more parameters in Proxy Error Reading From Remote Server Returned By /users/sign_in format .This additional hexadecimal code are the address of the memory locations where the instruction(s) was loaded at the time of the error.

What causes Proxy Error Reading From Remote Server Returned By /users/sign_in error?

The Proxy Error Reading From Remote Server Returned By /users/sign_in error may be caused by windows system files damage. The corrupted system files entries can be a real threat to the well being of your computer.

There can be many events which may have resulted in the system files errors. An incomplete installation, an incomplete uninstall, improper deletion of applications or hardware. It can also be caused if your computer is recovered from a virus or adware/spyware
attack or by an improper shutdown of the computer. All the above actives
may result in the deletion or corruption of the entries in the windows
system files. This corrupted system file will lead to the missing and wrongly
linked information and files needed for the proper working of the
application.

How to easily fix Proxy Error Reading From Remote Server Returned By /users/sign_in error?

There are two (2) ways to fix Proxy Error Reading From Remote Server Returned By /users/sign_in Error:

Advanced Computer User Solution (manual update):

1) Start your computer and log on as an administrator.

2) Click the Start button then select All Programs, Accessories, System Tools, and then click System Restore.

3) In the new window, select «Restore my computer to an earlier time» option and then click Next.

4) Select the most recent system restore point from the «On this list, click a restore point» list, and then click Next.

5) Click Next on the confirmation window.

6) Restarts the computer when the restoration is finished.

Novice Computer User Solution (completely automated):

1) Download (Proxy Error Reading From Remote Server Returned By /users/sign_in) repair utility.

2) Install program and click Scan button.

3) Click the Fix Errors button when scan is completed.

4) Restart your computer.

How does it work?

This tool will scan and diagnose, then repairs, your PC with patent
pending technology that fix your windows operating system registry
structure.
basic features: (repairs system freezing and rebooting issues , start-up customization , browser helper object management , program removal management , live updates , windows structure repair.)

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.

  • 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>();
            });*/
      }
  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Ubuntu Servers, Cloud and Juju
  • Server Platforms
  • [SOLVED] Apache2 reversy proxy fail to pass to connection to backend with ssl

  1. Apache2 reversy proxy fail to pass to connection to backend with ssl

    Hi,

    im having this problems almost a week now, and i have no idea how to solve this,

    i have a apache2 reverse proxy (with ssl) passing the connection to another server running tomcat with ssl. i keep getting this error message on browser

    Proxy Error

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

    Reason: Error reading from remote server

    on the error logs it says

    [Mon Sep 29 11:29:43.494799 2014] [proxy_http:error] [pid 2221:tid 140582592702208] (103)Software caused connection abort: [client 192.168.12.94:37724] AH01102: error reading status line from remote server xxx.xxx.xxx:443
    [Mon Sep 29 11:29:43.494992 2014] [proxy:error] [pid 2221:tid 140582592702208] [client 192.168.12.94:37724] AH00898: Error reading from remote server returned by /

    however it works if i passed it through non ssl tomcat.. need help on this matter.. below is the setting for my proxy configuration

    Code:

    SSLSessionCache        shmcb:/home/gpki/ssl_scache(512000)
    SSLSessionCacheTimeout  300
    Servername xxx.xxx.xxx
    
    <VirtualHost *:443>
    
        SSLEngine On
        SSLProxyEngine On
    
    SSLProxyCheckPeerCN off
    SSLProxyCheckPeerExpire off
    SSLProxyCheckPeerName off
    
    SSLProxyProtocol all
    SSLProxyVerify optional_no_ca
    
        ProxyRequests Off
        ProxyPreserveHost On
    
        SSLCertificateFile /etc/apache2/ssl/server.crt
        SSLCertificateKeyFile /etc/apache2/ssl/serverkey.key
        SSLCACertificateFile /etc/apache2/ssl/verisign.crt
    
    #    ProxyHTMLInterp On
    #    ProxyHTMLExtended On
    
        ProxyPass / https://xxx.xxx.xxx/
        ProxyPassReverse / https://xxx.xxx.xxx/
    
        SetEnv proxy-initial-not-pooled
        SetEnv proxy-nokeepalive 1
    
    
    </VirtualHost>

    thanks

    Last edited by lesbianpenguin; September 29th, 2014 at 11:20 AM.

    Reason: solve


  2. Re: Apache2 reversy proxy fail to pass to connection to backend with ssl

    managed to solve it… need to configure tomcat to allow only sslv3 to make it work


Bookmarks

Bookmarks


Posting Permissions

Понравилась статья? Поделить с друзьями:
  • Error reading from remote server apache
  • Error processing update albion online
  • Error reading from file битрикс
  • Error processing tar file exit status 1 unexpected eof
  • Error reading from file verify that the file exists and that you can access it