How to connect to a managed MongoDB instance on AWS

How to connect to a managed MongoDB instance on AWS from your local client.

When creating a managed MongoDB instance on AWS via Qovery, you don't get a publicly accessible endpoint. While it is good from a security point of view, you still might need to connect to it from a local client.

Goal

This tutorial will show you how to connect to your managed MongoDB instance private endpoint from your local machine, through your EKS cluster.

  1. Open two terminal windows with access to your Kubernetes cluster

    We will need to run two different commands to forward your local traffic to your database.

  2. Export the required environment variables

    In each terminal window, export some env variables:

    export SERVICE_NAME=mongodb-tunnel
    export ENDPOINT=<the private endpoint to your db from your AWS console>
    export PORT=<your DB port>
    export LOCAL_PORT=8080 # you can use any other port available on your computer
  3. Run a socat container in your cluster

    socat is a relay for bidirectional data transfers between two independent data channels. It will forward all traffic between your computer and your database.

    kubectl run ${SERVICE_NAME} --image=alpine/socat \
    -it --tty --rm --expose=true --port=${PORT} \
    -- \
    tcp-listen:${PORT},fork,reuseaddr \
    tcp-connect:${ENDPOINT}:${PORT}
  4. Start port-forwarding to your socat pod

    To access your socat pod from your container you will need to start a port-forwarding.

    kubectl port-forward service/${SERVICE_NAME} ${LOCAL_PORT}:${PORT}
  5. Download the MongoDB certificate

    Connections to MongoDB instances on AWS use TLS. You will need the certificate to connect. You can download it here: https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem

  6. Connect to your DB instance

    In this example we are using the Mongo Shell, but you can use any other client to connect to it. The credentials are available on the Qovery console.

    mongosh --host 127.0.0.1 \
    --port ${LOCAL_PORT} \
    --username <username> \
    --tls --tlsCAFile <path to downloaded PEM>/rds-combined-ca-bundle.pem \
    --tlsAllowInvalidCertificates