Connecting to an Amazon DocumentDB Cluster from Outside an Amazon VPC - Amazon DocumentDB

Connecting to an Amazon DocumentDB Cluster from Outside an Amazon VPC

Amazon DocumentDB (with MongoDB compatibility) clusters are deployed within an Amazon Virtual Private Cloud (Amazon VPC). They can be accessed directly by Amazon EC2 instances or other AWS services that are deployed in the same Amazon VPC. Additionally, Amazon DocumentDB can be accessed by EC2 instances or other AWS services in different VPCs in the same AWS Region or other Regions via VPC peering.

However, suppose that your use case requires that you (or your application) access your Amazon DocumentDB resources from outside the cluster's VPC. In that case, you can use SSH tunneling (also known as port forwarding) to access your Amazon DocumentDB resources.

It is beyond the scope of this topic to discuss SSH tunneling in depth. For more information about SSH tunneling, see the following:

To create an SSH tunnel, you need an Amazon EC2 instance running in the same Amazon VPC as your Amazon DocumentDB cluster. You can either use an existing EC2 instance in the same VPC as your cluster or create one. For more information, see the topic that is appropriate for your operating system:

You might typically connect to an EC2 instance using the following command.

ssh -i "ec2Access.pem"

If so, you can set up an SSH tunnel to the Amazon DocumentDB cluster by running the following command on your local computer. The -L flag is used for forwarding a local port. When using an SSH tunnel, we recommend that you connect to your cluster using the cluster endpoint and do not attempt to connect in replica set mode (i.e., specifying replicaSet=rs0 in your connection string) as it will result in an error.

ssh -i "ec2Access.pem" -L -N

After the SSH tunnel is created, any commands that you issue to localhost:27017 are forwarded to the Amazon DocumentDB cluster sample-cluster running in the Amazon VPC. If Transport Layer Security (TLS) is enabled on your Amazon DocumentDB cluster, you need to download the public key for Amazon DocumentDB from . The following operation downloads this file:


TLS is enabled by default for new Amazon DocumentDB clusters. However, you can disable it. For more information, see Managing Amazon DocumentDB Cluster TLS Settings.

To connect to your Amazon DocumentDB cluster from outside the Amazon VPC, use the following command.

mongo --sslAllowInvalidHostnames --ssl --sslCAFile rds-combined-ca-bundle.pem --username <yourUsername> --password <yourPassword>