我在Raspberry Pi上设置了nginx以便在端口5000上运行dotnet核心Web api。我在Pi上没有防火墙,并且我禁用了SSL重定向,因此可以使用telnet这样运行GET请求:
telnet localhost 5000
GET /api/test HTTP/1.1
host: localhost
按预期工作。我的问题是,使用telnet 192.168.1.10 5000
之类的机器的内部IP地址时,这种方法不起作用。相反,我得到了:
telnet: Unable to connect to remote host: Connection refused
我已将nginx设置为反向代理,以便也为我的网站提供服务。这是我的nginx.conf:
user www-data;
work_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv.1.1 TLSv1.2
ssl_prefer_server_ciphers on;
acces_log /var/log/nginx/access.log;
error_log /var/nginx/error.log;
gzip on;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
这是我在启用了站点的服务器中的配置:
server {
listen 80 default_server;
server_name mywebsite.com www.mywebsite.com;
root /srv/www/mywebsite.com;
index index.html;
location /api {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Connection keep-alive;
}
}
如果我可以通过本地主机正常连接,为什么我无法通过其内部IP连接到同一台计算机?
答案:
通过使用netstat -tulpn | grep LISTEN
检查端口,我发现我的dotnet应用程序仅在127.0.0.1:5000上侦听,而不是在所有IP地址上侦听。为了使应用程序在所有IP地址上进行侦听,我在应用程序的UseUrls()
文件中设置了主机生成器的Program.cs
:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls(urls: new String[] { "http://*:5000", "https://localhost:5001" });
});
我无法获得appsettings.json
文件没有任何效果,但是该文件有效,现在我可以从其内部IP地址访问该api。