.NET Core App Connection String to Mongodb running in Docker

Hello Everyone,
I have my MongoDB running in Docker in the Amazon Linux EC2 instance in AWS. It has the SSL/TLS Certificate as well. On the Server, I have to add the tlscertificate and CArootfile to open the mongodb.
First question: is it possible to add tls certificate in conf file and restart the mongodb? and if so, how can I add it? and What is the command to restart the mongodb to accept the tls certificate.? Sudo/systemctl doenst work in the docker
Second question: I was able to connect to MongoDB to my local MongoDB compass, Now I am trying to run it on my .NET Core application with those certificates, it doesnt work.
Here is my C# code to

string conn = @"mongodb://abcdef:1234667@ec2instance.compute.amazonaws.com:27017/?tls=true";
var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(conn));
                clientSettings.AllowInsecureTls = false;
                clientSettings.UseTls = true;

                SslSettings sslSettings = new SslSettings
                {
                    EnabledSslProtocols = SslProtocols.Tls12,
                    ClientCertificates = new[] { 
                                                    new X509Certificate(@"mongodb.pem"),
                                                    new X509Certificate(@"rootCA.crt"),
                                                },
                };

                clientSettings.SslSettings = sslSettings; 

                MongoClient client = new MongoClient(clientSettings);

And the error I got is:

{"A timeout occurred after 30000ms selecting a server using CompositeServerSelector
	{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, 
	LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. 
Client view of cluster state is { ClusterId : \"1\", Type : \"Unknown\", State : \"Disconnected\", Servers : [{ ServerId: \"
{ ClusterId : 1, EndPoint : \"Unspecified/ec2-52-28-11-2.eu-central-1.compute.amazonaws.com:27017\" }\", 
EndPoint: \"Unspecified/ec2-52-28-11-2.eu-central-1.compute.amazonaws.com:27017\", ReasonChanged: \"Heartbeat\", 
State: \"Disconnected\", ServerVersion: , TopologyVersion: , Type: \"Unknown\", 
HeartbeatException: \"MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server.\r\n 
---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: PartialChain\r\n   
at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)\r\n   
at System.Net.Security.SslStream.CompleteHandshake(SslAuthenticationOptions sslAuthenticationOptions)\r\n   
at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)\r\n   
at System.Net.Security.SslStream.AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions)\r\n   
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)\r\n   
at MongoDB.Driver.Core.Connections.SslStreamFactory.CreateStream(EndPoint endPoint, CancellationToken cancellationToken)\r\n   
at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelper(CancellationToken cancellationToken)\r\n   
--- End of inner exception stack trace ---\r\n   
at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelper(CancellationToken cancellationToken)\r\n   
at MongoDB.Driver.Core.Connections.BinaryConnection.Open(CancellationToken cancellationToken)\r\n   
at MongoDB.Driver.Core.Servers.ServerMonitor.InitializeConnection(CancellationToken cancellationToken)\r\n   
at MongoDB.Driver.Core.Servers.ServerMonitor.Heartbeat(CancellationToken cancellationToken)\", 
LastHeartbeatTimestamp: \"2022-08-31T14.22.15.1629747Z\", LastUpdateTimestamp: \"2022-08-31T14.22.15.1629749Z\" }] }."}

Any suggestions??

Create a folder and create a customized config file along with certificate files and write a customized “dockerfile” to copy them into corresponding directories inside the container. do not forget to set in-out ports.

for accessibility, you will need port forwarding, one from container to aws network, and from there to WAN (if it is not done in one step).

Timeout errors are mostly caused by an incorrect address or port to the server, and then any firewall, proxy, VPN, or connection-limiting program can be the next culprit. I am guessing yours is incomplete port forwarding or AWS firewall setting. check them first.

Hello Yilmaz_Durmaz
Thank you so much for the info. I am a bit confused about this. Please bear with me as I am completely new to Docker and Linux environment. and I am still reading upon how the MongoDB, tls and its commands.
The thing is, I can connect directly to the MongoDB Compass with the tls certificate file copied locally to my local environment. Now, I am using the same connection string into my application with those files to make it work. but its not connecting.

does it make any difference if I add the docker file to the container or add those certificates to my application?

I assume you use your own MongoDB server in a container, not an Atlas cluster. That should give 3 running machines; your local, app somewhere on the cloud, and container somewhere else.

  • you can develop on your local, but have to deploy at some point, so you need lots of settings on the cloud side.
  • database ports should be accessible at least from app’s network (and your local to test it)
  • assuming you have succesfully set security on the container, you need you public key copied to your local AND app server so you can connect to the database. (this might the step you haven’t done)
    • you need to also set your app to use this new auth.

setting and running containers is another story but you seem to have set up your database authorization from your description (connecting with a key from local). then all you need to copy the required keys to your app’s host and set your app to connect to the database with a key.

All that said, your first code shows you have already set something. Unfortunately, I am not a .NET guru, so I cannot say if this is the right way to use the key along with a username/password.

Run your app first on your local environment to see if it runs fine. This will eliminate the possibility of the wrong implementation.

Then, you will need to set firewalls, port forwardings, and CORS (if needed) so that app’s and database’s hosts can connect to each other.