Ngrok 502 bad gateway как исправить

Quite new to using any sort of Web App stuff, and I’ve been trying to slowly build a Facebook Messenger Bot. When I try to use ngrok I can’t visit the address I’m given, i.e:

ngrok http 5000

is what I’m putting in the command line, and it’s returning this:

ngrok by @inconshreveable

Session Status                online
Version                       2.1.18
Region                        United States (us)
Web Interface                 http://127.0.0.1:4040
Forwarding                    http://ea986ca5.ngrok.io -> localhost:5000
Forwarding                    https://ea986ca5.ngrok.io -> localhost:5000

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

But when I take the address ‘https://ea986ca5.ngrok.io’ as is required by the Facebook developer’s page, it says:

The connection to http://ea986ca5.ngrok.io was successfully tunneled to your
ngrok client, but the client failed to establish a connection to the local  
address localhost:5000.


Make sure that a web service is running on localhost:5000 and that it is a 
valid address.


The error encountered was: dial tcp [::1]:5000: connectex: No connection 
could be made because the target machine actively refused it.

Is it a problem with my local port? Thanks!

asked Nov 14, 2016 at 21:51

Jordan Cagney's user avatar

7

This worked for me

ngrok.exe http --host-header=rewrite localhost:<Your Port number>

e.g:

ngrok.exe http --host-header=rewrite localhost:5219

Im using visual studio 2017 dont know if it effects anthing.

Faizan Mubasher's user avatar

answered Mar 28, 2017 at 12:00

2

Try to explicitly set the localhost IP:

ngrok http 127.0.0.1:5000 instead of ngrok http 5000

Good luck!

answered Oct 9, 2018 at 15:06

Sasha's user avatar

SashaSasha

5474 silver badges7 bronze badges

1

Just as @njzk2 should have said, if you don’t have a web server running so it cannot work. I would like to make it clearer to you, if you are still confused.

What ngrok does, is to make your local server (running on localhost) to be available to the outside world (rest of the internet). On its own, it is not a web server. So for your bot development you need to have a web server running on a defined port (which in your case is 5000). Then you can point ngrok to this port so that it will redirect requests sent to your public address to the program running on that port.
The web server will then accept and handle requests from Facebook

answered Dec 16, 2016 at 3:55

Ken4scholars's user avatar

Ken4scholarsKen4scholars

6,0282 gold badges21 silver badges38 bronze badges

I found I had to remove the quotes around the -host-header section to get this to work with the latest ngrok version (2.3.35):

ngrok http https://localhost:5001 -host-header=localhost:5001

(Currently not enough rep to add comments on any of the answers above)

answered Jun 9, 2020 at 10:23

8a9's user avatar

8a98a9

5035 silver badges11 bronze badges

0

Step 1 — Register to ngrok and download .exe file in dashboard page

Step 2 — Open terminal and copy & paste from the dashboard the line without ./

Step 3 — run your localhost

Step 4 — If step 2 was successfully done, paste in the same terminal (step 2) the line with your localhost port

ngrok http https://localhost:44386 -host-header=»localhost:44386″

Step 5 — Copy the URL generated in the terminal and waalla.. you can ping to it.


In case of <<<<Ngrok errors ‘502 bad gateway’>>>> change https into http so the Step 4 will be ngrok http http://localhost:44386 -host-header=»localhost:44386″

answered Jun 8, 2020 at 9:18

Oltion Driza's user avatar

1

Try like below:

ngrok http 127.0.0.1:8080 -host-header="127.0.0.1:8080"

answered Mar 6, 2019 at 2:29

licaomeng's user avatar

licaomenglicaomeng

9092 gold badges13 silver badges27 bronze badges

1

It seems that this issue has now been resolved in the latest version of ngrok: https://github.com/inconshreveable/ngrok/issues/448

Basically, what you do is to specify that you are using https like this:

ngrok http https://localhost:54321 -host-header="localhost:54321"

At least, this resolved the issue for me. Replace 54321 with your actual port number.

answered Apr 14, 2020 at 7:17

Eyvind's user avatar

EyvindEyvind

5,2115 gold badges40 silver badges58 bronze badges

In my case, it was the project in Visual Studio 2017 .Net Core 2.1 was created to use https with a self-signed certificate. If you don’t need your localhost to be https, then what fixed it for me was creating a new web project and unchecking https. When you run ngrok (ngrok http port-number-from-IISExpress) it provides you with an https url you can use for development.

answered Feb 15, 2019 at 17:38

Cliff Coulter's user avatar

For me, switching the protocol from http to tls worked since I am forwarding only a secure connection. I didn’t need to rewrite the header.

Just for context, I am forwarding a connection to a running docker container on Ubuntu 16.

PS: You still access the address using https in the browser, not tls.

answered Jul 30, 2018 at 14:08

AndyFaizan's user avatar

AndyFaizanAndyFaizan

1,82321 silver badges29 bronze badges

MAKE SURE SERVER LISTENS ON THE SAME PORT WHERE NGROK IS TUNNELED

In my case I was running ngrok using ‘ngrok HTTP 3002’, while my express server was running at port 5000, hence throwing BAD GATEWAY error.

I restarted ngrok on port 5000 and it worked like a charm.

answered Mar 3, 2021 at 1:04

Hassaan Anwar's user avatar

502 gateway error occurs because ngrok not able to receive any reponse from Localhost.

The things need to be done is :

  1. Start a webserver in a Port
  2. Trigger ngrok command in that Port.

What I have done is

  • Started a tomcat Web Server in 8080.
  • Then Triggered ngrok http 8080.

It works really cool …
Try this …..
Hope it works for You .

Angel F Syrus's user avatar

answered Oct 22, 2019 at 5:49

Dhana_Siggie's user avatar

If you just with to use ngrok to intercept incoming data, and you do not have a local webserver for whatever reason, then you can use ncat.

nc -l 5000

This will create a process that listens on port 80.

So when used in combination with

ngrok http 5000

You will no longer get the ‘502 bad gateway’ error.

answered Nov 9, 2019 at 0:14

Jeroen Ritmeijer's user avatar

Jeroen RitmeijerJeroen Ritmeijer

2,7733 gold badges24 silver badges31 bronze badges

I had to put my server ip address and works perfect!

./ngrok http [ip server]:5000

answered Aug 17, 2020 at 23:21

Javier Rodriguez's user avatar

i had the same issue,

because, i forgot to run the localhost:3000 port, which was supposed to be running some node server.

after i run node server, then i run, ngrok http 3000, so that it will cloud that node server in ngrok for globally access in internet.

answered Feb 28, 2021 at 18:09

AniX Sharma's user avatar

I have solved the issue by killing the processes. Only 4 processes are allowed.

First command top to see your streamlit processes. You will see:

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND

Just type kill PID [PID VALUE] and re-run the cell.

answered Jul 26, 2021 at 9:58

vagitus's user avatar

vagitusvagitus

2542 silver badges10 bronze badges

I finally made it 😭

ngrok http 80 

and then start another service on ur localhost:80… in my case, I use these

php -S localhost:80

and for reverse shell stuffs ..

nc -nlvp 80

Your problem is now fixed. ^_^

answered Mar 5, 2022 at 11:43

Gray Hat's user avatar

Sometimes what causes this error is your firewall that is blocking the connection.
to access the firewall in windows:

  1. press win +r
  2. type in firewall.cpl
  3. go to allow apps through windows defender
  4. below tap on allow another app.
  5. locate the ngrok.exe file.

This worked for me.

answered Jul 15, 2022 at 13:24

George's user avatar

If you want to host your local service, then the command you to use is: ngrok http 8000.
If it still doesn’t work and shows same then rewrite the host header using: ngrok http 8000 --host-header rewrite.

answered Feb 16 at 5:50

Anish Var Shrestha's user avatar

I found it the hard way to solve this issue.

  1. Make sure you use the correct port and «then» use ngrok (eg.3000). You have to run both ngrok and node simultaneously.
  2. Use correct endpoint on both code and on the Callback URL
  3. The response is a big json and you have to return req.query["hub.challenge"] as an Integer/Number.

Tip: Use ngrok http 127.0.0.1:3000

enter image description here

answered Apr 10 at 14:26

Baalamurgan's user avatar

BaalamurganBaalamurgan

1512 silver badges7 bronze badges

This error can occur if you have an HTTP rule to redirect HTTP to HTTPS.

You can disable this for your developer machine or add a custom rule based on the X-Original-Host header:

I’m using the IIS rewrite plug-in and this is how I fixed it

 <rule name="Redirect to https" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
            <match url=".*" negate="false" />
            <conditions logicalGrouping="MatchAll">
              <add input="{HTTPS}" pattern="off" />

              <add input="{HTTP_X_Original_Host}" pattern="yourngrokname.ngrok.io" negate="true" />             

            </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
          </rule>

answered Sep 17, 2017 at 6:54

Simon_Weaver's user avatar

Simon_WeaverSimon_Weaver

138k81 gold badges639 silver badges680 bronze badges

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

Comments

@tanvishah-syn

Hi, I have installed ngrok version 2.2.8 on mac. I am trying to send http request to server using postman. A request is sending correctly. I am able to see headers in http://127.0.0.1:4040 ngrok web interface. I am getting a response as » 502 Bad Gateway. The server returned an invalid or incomplete response.» How would I debug ngrok request?

scrummitch, jefflam, armordog, ivanpetrushev, momsse, sfmskywalker, sharonmalio, parulagg27, johngeorgewright, drphelps, and 14 more reacted with thumbs up emoji

@dannyfreed

This just started happening to me. Any suggestions/fixes? Nothing knowingly changed on my end as of late…

@scrummitch

bump on this, it seems to happen when i paste it into the facebook sharing debugger

@jefflam

Getting this error too — anyone resolution..?

@harksha

+1. v2.2.8 running on windows 10.

@Joe118

+1 v2.2.8, v2.2.9, and v2.2.7 on windows server 2008. Getting this text:

502 Bad Gateway
The server returned an invalid or incomplete response.

@Joe118

Well I am able to see localhost:4040 (which is the introspection page) through the tunnel, so its some disagreement between ngrok and my application. It’d be really nice if ngrok would log somewhere WHAT it did not like.

@harksha

Try running it without ssl

@Joe118

Thanks @harksha — examining the documentation for how to ;)

EDIT — you probably mean adding -bind-tls=false — that did not work:

Incorrect Usage: flag provided but not defined: -bind-tls

@Joe118

@harksha I see you posted 10 days ago that you had this problem, would appreciate figuring out which version of ngrok worked for you and what combo of command line options :)

THANKS!

@harksha

@Joe118 No, I mean you need to disable ssl on your local solution, so it runs on http, not https

@Joe118

@harksha my http server already was running on http only.

Anyways I’m pretty convinced this is not a problem with ngrok because I can direct ngrok to forward port 4040 (its own diagnostic) and then I can see it fine on the ngrok.io subdomain. So its something to do with my http server.

I still can’t figure out why the port forwarding would cause a 502, because I can see the web page when I run a web browser on the same machine and look at it via localhost:8000/index.html

@harksha

@Joe118 ok, I thought that’s what fixed it, but you’re right, it might be port forwarding(which got stopped when I removed ssl). Don’t have any idea why, tho’.

@Joe118

@harksha thanks!

I’m going to chat with the people who wrote the embedded web server I’m using — EmbedIO. I’ll report back here if they find anything.

@Joe118

@Joe118

OK its not an ngrok bug and not a bug in EmbedIO either. :)

The issue is that when you tell a webserver to serve pages on http://localhost:8787/ (as an example), some also bind http://127.0.0.1:8787/ and some do not. There’s no rule that the webserver has to, but also no rule that it does NOT have to. So to be sure ngrok will tunnel your web server, you have to bind both localhost:8787 and 127.0.0.1:8787

@inconshreveable , so now the question becomes, did anything change in ngrok recently to require both localhost and 127.0.0.1 to be bound?

@sharonmalio

Hey so you will need to start your server manually so that it listens on the port you want.
Run php -S 0.0.0.0:5000 -t public/ on linux command line with 5000 being the port you wanna feed to ngrok. Then go to ngrok and run ngrok http 5000

That will work

@andyfaizan

Switching the protocol from http to tls worked for me.

@seannybgoode

switching from http to tls killed the 502 error for me, but now i’m getting an invalid hostname 4xx error

@syberkitten

Also getting the bad gateway for connecting to localhost running an HTTPS (TLS) server on port 9011.
When switching to HTTP (not HTTPS) it works.

Any new ideas?

@amardesaiZT

This is what worked for me.
Spent hours searching for it. Some of the above solution didn’t work.
I would recommend this order.
ngrok http https://localhost:5443 -host-header=»localhost:5443″ -subdomain=
ngrok http https://localhost:5443 -host-header=»localhost:5443″

Joe118, amarmechai, liamhart96, nxanil, random82, ykmsm, mayavuser, Rene-Sackers, kris48k, magisters-cc, and 9 more reacted with thumbs up emoji
Efaz95 reacted with hooray emoji

@nanddeepn

Ngrok expects a web server to be running on localhost. If there isn’t a server running, you’ll see a 502 error .

@karls

I also ran into the same issue with testing some webhooks locally. In my case, I had to make sure ngrok was tunneling to my local development server running on HTTPS, not HTTP.

@dhanaSiggie1111

Hi tanvish,

502 gateway error occurs because ngrok not able to receive any reponse from Localhost.

The things need to be done is : 1.Start a webserver in a Port 2.Trigger ngrok command in that Port.

What i have done is -> Started a tomcat Web Server in 8080. -> Then Triggered ngrok http 8080.

It works really Kool .. Try this .. Hope it works for You .

@Nightrider0098

just use
ngrok http port_number
it works

heniotierra and extremecode0xFF reacted with thumbs up emoji
rayk47, giannidhooge, arielkaluzhny, MicicFilip, OsmarSalvatori, AdityaAugustaFirmansyah, gurinder-trantor, sheshankdebugged, kambielawski, kris48k, and 15 more reacted with thumbs down emoji

@phelps-matthew

For linux users w/ default port 80:

sudo apt-get install apache2
sudo service apache2 start
ngrok http 80
  • Make sure port 80 is allowed through firewall
  • place sample html file in /var/www/html/index.html

@mudirajesh

Sudo not install on Android phone when i using termux .

@heniotierra

Студворк — интернет-сервис помощи студентам

Это у меня класс бота

Кликните здесь для просмотра всего текста

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramWebhookBot;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
 
//Аннотация @Component необходима, чтобы наш класс распознавался Spring, как полноправный Bean
@Component
public class Bot extends TelegramWebhookBot {
 @Value("${bot.name}")
 private String botUsername;
 
 @Value("${bot.token}")
 private String botToken;
 
 @Value("${bot.webhook.path}")
 private String botPath;
 
@Override
public BotApiMethod onWebhookUpdateReceived(Update update) {
    if (update.hasMessage() && update.getMessage().hasText()) {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(update.getMessage().getChatId().toString());
        sendMessage.setText("test");
        return sendMessage;
    }
    return null;
}
 
@Override
public String getBotUsername() {
    return botUsername;
}
 
@Override
public String getBotPath() {
    return botPath;
}
 
@Override
public String getBotToken() {
    return botToken;
}
 
}

А так я запускаю (все работает при longpolling) запускаю через Тор

Кликните здесь для просмотра всего текста

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
    public static void main(String[] args) {
        
        System.getProperties().put( "proxySet", "true" );
        System.getProperties().put( "socksProxyHost", "127.0.0.1" );
        System.getProperties().put( "socksProxyPort", "9150" );
        // Здесь код написан по заветам
        // https://github.com/rubenlagus/TelegramBots/tree/master/telegrambots-spring-boot-starter
        ApiContextInitializer.init();
 
        SpringApplication.run(Main.class, args);
    }
}

Ну вот пробую перенести на webhook:
Запускаю так ngrok http 80 —host-header=site.local
всегда после запуска ngrock я регаю URL в телеге и получаю ответ: «Webhook was set»
Далее когда я запускаю бота, он не начинает работать, ошибок не выдает, но сразу же выключается.
по ардесу http://127.0.0.1:4040/inspect/http я вижу свои запросы но они с 5** ошибкой:
если я запускаю по порту который указал в Main методе для Тора, то ошибка 501 Tor is not an HTTP Proxy
при том, тело POST запроса содержит нужные мне данные которые мне передал телеграмм что от кого когда куда и тд но получить и обработать ботом я их не могу.

если я запускаю так ngrok http 8080 —host-header=site.local то ошибка 502 Bad Gateway с коментом
The connection was closed before this request could be fully read; 218 bytes were captured. It cannot be replayed. The error encountered while reading the request body was «unexpected EOF».

что я делаю не так?

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

enter image description here

Соединение с https://da003848.ngrok.io было успешно настроено для подключения к вашему клиенту ngrok, но клиенту не удалось установить соединение с локальным адресом localhost: 3000.

Я также вижу ошибку 502 ниже;

Session Status                online                                                                                     
Account                       whileymai (Plan: Free)                                                                     
Version                       2.3.35                                                                                     
Region                        United States (us)                                                                         
Web Interface                 http://127.0.0.1:4040                                                                      
Forwarding                    http://da003848.ngrok.io -> http://localhost:3000                                          
Forwarding                    https://da003848.ngrok.io -> http://localhost:3000                                         

Connections                   ttl     opn     rt1     rt5     p50     p90                                                
                              2       0       0.01    0.00    0.00    0.00                                               

HTTP Requests                                                                                                            
-------------                                                                                                            

GET /favicon.ico               502 Bad Gateway                                                                           
GET /

                      502 Bad Gateway   

Не уверен, как это исправить. Спасибо

2 ответа

Вы показываете два разных туннеля нгрок.

Консоль туннелирует к da003848, а приложение Shopify указывает на fb393d38.

Вам нужно использовать ngrok premium для установки туннеля статического домена или обновлять URL-адрес приложения Shopify каждый раз, когда вы запускаете службу ngrok, поскольку она будет меняться каждый раз, когда вы пользуетесь бесплатным тарифом.

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


0

drip
21 Апр 2020 в 11:13

Когда ваш терминал включен, ngrok вернет тот же URL, но когда вы перезапустите ngrok, он создаст VPN с новым URL. Вы также можете зарегистрироваться, тогда она будет работать постоянно, пока ваша система не будет включена. Нажмите здесь, чтобы создать учетную запись и получить YOUR_AUTHTOKEN

$ ngrok authtoken <YOUR_AUTHTOKEN>


0

Kshitij Verma
21 Апр 2020 в 17:58

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

Пошаговое руководство

Вот простой тестовый файл:

$ cat t.html 
<body>
    <h1>test</h1>
</body>

Запускаем простой http-сервер на localhost:

python -m SimpleHTTPServer 7070

Запуск ngrok

$ ngrok http 7070

grok by @inconshreveable                                                                                                                                                                   (Ctrl+C to quit)
                                                                                                                                                                                                            
Session Status                online                                                                                                                                                                        
Session Expires               7 hours, 59 minutes                                                                                                                                                           
Update                        update available (version 2.2.8, Ctrl-U to update)                                                                                                                            
Version                       2.2.4                                                                                                                                                                         
Region                        United States (us)                                                                                                                                                            
Web Interface                 http://127.0.0.1:4040                                                                                                                                                         
Forwarding                    http://4580e823.ngrok.io -> localhost:7070                                                                                                                                    
Forwarding                    https://4580e823.ngrok.io -> localhost:7070                                                                                                                                   
                                                                                                                                                                                                            
Connections                   ttl     opn     rt1     rt5     p50     p90                                                                                                                                   
                              0       0       0.00    0.00    0.00    0.00          

Проверка

curl -D - https://4580e823.ngrok.io/t.html
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/2.7.10
Date: Tue, 23 Oct 2018 20:03:45 GMT
Content-type: text/html
Content-Length: 33
Last-Modified: Tue, 23 Oct 2018 19:53:09 GMT
Connection: keep-alive

<body>
    <h1>test</h1>
</body>

Вот и все

Понравилась статья? Поделить с друзьями:
  • Как найти папку office
  • Как найти тангенциальное ускорение через уравнение
  • Как найти катю в метро
  • Как найти интеграл деления
  • Как найти недавно открытые файлы