首页 > 解决方案 > 无法访问部署到 ubuntu 的 .Net Core 2.1 Web 应用程序

问题描述

我有一个 .NET core 2.1 Web 应用程序部署到在 nginx 上运行 ubuntu 18.04 的 VPS(我有 root 访问权限)。直到我最后一次更新服务器上的文件之前,一切都很顺利,我不明白它是如何停止工作的。它在我的本地机器上完美运行,但在服务器上以某种方式重定向到 HTTPS 失败。

Program.cs 代码

namespace MyApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .CaptureStartupErrors(true)
                .UseSetting("detailedErrors", "true")
                .UseStartup<Startup>()
                .Build();
    }
}

启动设置.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:55533",
      "sslPort": 44388
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MyApp-Dev": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5000;https://localhost:5001",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

应用设置.json

{
  "Kestrel": {
    "EndPoints": {
      "Http": {
        "Url": "http://localhost:5000"
      },

      "httpsdefaultcert": {
        "url": "https://localhost:5001"
      }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information"
    }
  },
  "AllowedHosts": "*"
}

红隼配置文件

[Unit]
Description=My App

[Service]
WorkingDirectory=/var/www/myapp.com/
ExecStart=/usr/bin/dotnet /var/www/myapp.com/MyApp.dll
Restart=always
RestartSec=10    # Restart service after 10 seconds if dotnet service crashes
KillSignal=SIGINT
SyslogIdentifier=dotnet-myapp.com
User=myuser
Environment=ASPNETCORE_ENVIRONMENT=Production

[Install]
WantedBy=multi-user.target

我第一次遇到类似问题时,我可以通过用“myuser”替换这个文件中的用户来解决它。以前,由于遵循了一些教程,我使用的是“www-data”。

Nginx 配置文件

upstream myapp.com {
    server localhost:5000;
}

server {
    listen 80;

    location ~ /.well-known {
        allow all;
        root /var/www/well-known;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    # Enable https and http/2
    listen *:443 ssl http2;

        # The certificate served by Let's encrypt can contain more than one domain which is very convenient
    server_name myapp.com;
    server_name www.myapp.com;
    ssl_certificate /etc/letsencrypt/live/www.myapp.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.myapp.com/privkey.pem; # managed by Certbot

        # security
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    ssl_ecdh_curve secp384r1;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;

        # Turn on OCSP stapling as recommended at
    # https://community.letsencrypt.org/t/integration-guide/13123
    # requires nginx version >= 1.3.7
    ssl_stapling on;
    ssl_stapling_verify on;

        # Uncomment this line only after testing in browsers,
    # as it commits you to continuing to serve your site over HTTPS in future
    # add_header Strict-Transport-Security "max-age=31536000";

    location / {
        proxy_pass  http://myapp.com;
    }
}

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

我确实尝试将上述文件中的用户从“www-data”更改为“myuser”,但由于它没有解决任何问题,我回到了以前的工作配置。


我将在这里留下我用来解决问题的步骤以及类似的步骤。任何有关我的方法的意见都非常受欢迎,即使您不知道如何帮助我解决这个特定问题。

1.防火墙:似乎配置正确!

须藤 ufw 状态

Status: active

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
443/tcp                    ALLOW       Anywhere
Nginx HTTP                 ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)
80/tcp (v6)                ALLOW       Anywhere (v6)
443/tcp (v6)               ALLOW       Anywhere (v6)
Nginx HTTP (v6)            ALLOW       Anywhere (v6)

2. Kestrel:似乎已经启动并运行了!不...

sudo systemctl status kestrel-myApp.service

● kestrel-myApp.service - My App
   Loaded: loaded (/etc/systemd/system/kestrel-myApp.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2019-02-16 06:46:25 UTC; 1h 6min ago
 Main PID: 1951 (dotnet)
    Tasks: 19 (limit: 4636)
   CGroup: /system.slice/kestrel-myApp.service
           └─1951 /usr/bin/dotnet /var/www/myApp/MyApp.dll

[错误提示]尽管如此,当我检查日志时,我能够找到这个:

Feb 16 06:46:26 localhost dotnet-myapp.com[1951]:       User profile is available. Using '/home/myuser/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
Feb 16 06:46:26 localhost dotnet-myapp.com[1951]: info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
Feb 16 06:46:25 localhost systemd[1]: Started My App.
Feb 16 06:46:20 localhost systemd[1]: /etc/systemd/system/kestrel-myapp.com.service:9: Failed to parse sec value, ignoring: 10    # Restart service after 10 seconds if dotnet service crashes
Feb 16 06:45:28 localhost systemd[1]: Failed to start My App.
Feb 16 06:45:28 localhost systemd[1]: kestrel-myapp.com.service: Failed with result 'signal'.
Feb 16 06:45:28 localhost systemd[1]: kestrel-myapp.com.service: Start request repeated too quickly.
Feb 16 06:45:28 localhost systemd[1]: Stopped My App.
Feb 16 06:45:28 localhost systemd[1]: kestrel-myapp.com.service: Scheduled restart job, restart counter is at 5.
Feb 16 06:45:28 localhost systemd[1]: kestrel-myapp.com.service: Service hold-off time over, scheduling restart.
Feb 16 06:45:28 localhost systemd[1]: kestrel-myapp.com.service: Failed with result 'signal'.
Feb 16 06:45:28 localhost systemd[1]: kestrel-myapp.com.service: Main process exited, code=killed, status=6/ABRT
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]:    at MyApp.Program.Main(String[] args) in C:\Users\myuser\Documents\Visual Studio 2017\Projects\MyApp\MyApp\Program.cs:line 34
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]:    at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]:    at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]:    at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String shutdownMessage)
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]:    at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]:    at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]:    at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.ValidateOptions()
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]:    at Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.Load()
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]: For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]: To generate a developer certificate run 'dotnet dev-certs https'. To trust the certificate (Windows and macOS only) run 'dotnet dev-certs https --trust'.
Feb 16 06:45:28 localhost dotnet-myapp.com[1893]: Unhandled Exception: System.InvalidOperationException: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found.

我能够在日志中多次看到这个问题,但在最近几个小时内没有发生。并且该网站仍然无法访问!我认为这是问题的根源,但我不知道如何解决它


3. Nginx : 似乎已经启动并运行,但...

sudo systemctl status nginx

● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2019-02-16 06:32:05 UTC; 1h 37min ago
     Docs: man:nginx(8)
 Main PID: 745 (nginx)
    Tasks: 4 (limit: 4636)
   CGroup: /system.slice/nginx.service
           ├─ 745 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           ├─ 746 nginx: worker process is shutting down
           ├─5455 nginx: worker process
           └─5456 nginx: worker process

须藤 nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

[错误提示]当我进入日志时,我确实看到了一些错误,这些错误并不是每次我无法访问网站时都会发生的:

2019/02/16 09:31:04 [error] 793#793: *7 connect() failed (111: Connection refused) while connecting to upstream, client: 123.2.45.130, server: myapp.com, request: "GET / HTTP/2.0", upstream: "http://127.0.1.1:5000/", host: "myapp.com"

4. 证书:看起来不错!

openssl s_client -connect localhost:443

CONNECTED(00000003)
depth=2 O = Digital Signature Trust Co., CN = DST Root CA X3
verify return:1
depth=1 C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
verify return:1
depth=0 CN = www.myapp.com
verify return:1
---
Certificate chain
 0 s:/CN=www.myapp.com
   i:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
 1 s:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
   i:/O=Digital Signature Trust Co./CN=DST Root CA X3
---
Server certificate
-----BEGIN CERTIFICATE-----
(...)
-----END CERTIFICATE-----
subject=/CN=www.myapp.com
issuer=/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: ECDH, P-384, 384 bits
---
SSL handshake has read 3634 bytes and written 334 bytes
Verification: OK
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
Server public key is 4096 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session: (...)

此外,当我尝试这个时,我得到了 A:https ://whatsmychaincert.com


5. 尝试从 localhost 检索内容

[错误提示]

wget http://localhost:5000

--2019-02-16 08:26:10--  http://localhost:5000/
Resolving localhost (localhost)... 127.0.0.1, 127.0.1.1, ::1
Connecting to localhost (localhost)|127.0.0.1|:5000... connected.
HTTP request sent, awaiting response... 307 Temporary Redirect
Location: https://localhost:5001/ [following]
--2019-02-16 08:26:10--  https://localhost:5001/
Connecting to localhost (localhost)|127.0.0.1|:5001... connected.
ERROR: cannot verify localhost's certificate, issued by ‘CN=localhost’:
  Unable to locally verify the issuer's authority.
To connect to localhost insecurely, use `--no-check-certificate'.

如输出中所建议的,不安全地运行命令,工作正常!

wget http://localhost:5000 --no-check-certificate

来源

为了配置服务器并部署应用程序,我使用了以下来源

https://www.meziantou.net/2017/04/25/publishing-an-asp-net-core-website-to-a-linux-host

https://odan.github.io/2018/07/17/aspnet-core-2-ubuntu-setup.html

https://www.meziantou.net/2017/04/25/adding-a-free-ssl-certificate-to-a-website-hosted-on-nginx-using-let-s-encrypt

https://docs.microsoft.com/en-gb/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-2.2

https://developingsoftware.com/aspnetcore-ubuntu/

标签: ubuntunginxasp.net-coreopensslkestrel-http-server

解决方案


我到达互联网的尽头来解决这个问题......以下两行解决了我的问题。我将它们添加到 FolderProfile.pubxml 文件中,因为我在部署到服务器之前一直发布到文件夹。

<AllowUntrustedCertificate>True</AllowUntrustedCertificate>
<UseMsDeployExe>true</UseMsDeployExe>

根据我的消息来源(如下),“将UseMsDeployExe错误更改为忽略证书,但不对用户进行身份验证,因此需要用户并通过(您要部署到的机器)”。尽管如此,我既没有指定用户也没有指定密码。

从 Visual Studio 2015 发布 - 允许不受信任的证书

关于如何解决我的问题的更多输入非常受欢迎!


推荐阅读