I have a droplet on DigitalOcean, and my application works fine when I use HTTP. However, when I try to enable HTTPS for added security, I encounter the following error when trying to run the application:
System.IO.IOException: Failed to bind to address https://0.0.0.0:5001: address already in use.
I’ve confirmed that nothing else is using this port, and the address appears free when I check. The problem only arises when I attempt to install the application. I am using self-signed certificates, and I’ve ensured they are correctly placed and accessible. But I can't seem to get past this issue.
Below are the relevant parts of my configuration and code:
My appsettings.json
{"ConnectionStrings": {"DefaultConnection": "YOUR_DB_CONNECTION_STRING" },"Logging": {"LogLevel": {"Default": "Debug","Microsoft": "Information","Microsoft.Hosting.Lifetime": "Information" } },"AllowedHosts": "*","Kestrel": {"Endpoints": {"Https": {"Url": "https://0.0.0.0:5001","Certificate": {"Path": "YOUR_CERT_PATH","KeyPath": "YOUR_CERT_KEY_PATH" } } } }}program.cs
namespace HIDDEN{ public class Program { public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); await host.RunAsync(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, config) => { var builtConfig = config.Build(); // Try to get connection string from configuration string configConnStr = builtConfig.GetConnectionString("DefaultConnection"); // Fallback to environment variable if needed string envConnStr = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING"); string finalConnectionString; if (!string.IsNullOrEmpty(configConnStr) && !configConnStr.Contains("${")) { Console.WriteLine("Using connection string from configuration."); finalConnectionString = configConnStr; } else if (!string.IsNullOrEmpty(envConnStr)) { Console.WriteLine("Using connection string from environment variable."); finalConnectionString = envConnStr; } else { Console.WriteLine("No valid connection string found."); finalConnectionString = ""; } Console.WriteLine($"Final connection string: {finalConnectionString}"); config.AddInMemoryCollection(new[] { new KeyValuePair<string, string>("ConnectionStrings:DefaultConnection", finalConnectionString) }); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseKestrel((context, options) => { // Allow Kestrel to load endpoints from appsettings.json options.Configure(context.Configuration.GetSection("Kestrel")); // SSL configuration from .pfx file string certPath = "YOUR_CERT_PATH"; string certPassword = "YOUR_CERT_PASSWORD"; // Password for the PFX file options.ListenAnyIP(5001, listenOptions => { listenOptions.UseHttps(certPath, certPassword); // Use SSL for HTTPS }); }) .UseStartup<Startup>(); }); }}