Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions menu/navigation.json
Original file line number Diff line number Diff line change
Expand Up @@ -2576,6 +2576,10 @@
"label": "Create a Database Instance",
"slug": "create-a-database-instance"
},
{
"label": "Connect a Database Instance to a Private Network",
"slug": "connect-database-private-network"
},
{
"label": "Connect to a Database Instance",
"slug": "connect-database-instance"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,6 @@ Managed Databases for PostgreSQL and MySQL are currently not compatible with the
You can use Public Gateways in [SSH bastion](/public-gateways/how-to/use-ssh-bastion/) mode and perform port forwarding.
</Message>

<Message type="tip">
If you are using Scaleway Kubernetes Kapsule, you can use the [scaleway-k8s-vpc](https://github.com/Sh4d1/scaleway-k8s-vpc) GitHub project to connect a Database Instance to your pods using a Private Network.<br /><br />
Once your Kapsule node is connected to the Private Network you can directly reach the database by using the assigned service IP. There is no need to expose it through a Kubernetes resource like a service. The database is ready to use out of the box. <br /><br />
**The `scaleway-k8s-vpc` is not an officially supported by Scaleway.**
</Message>

## How to detach a Database Instance from a Private Network

1. Click **PostgreSQL and MySQL** under **Managed Databases** on the side menu. A list of your Database Instances displays.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ Compared to traditional database management, which requires customers to provide
- Choose your storage type and capacity. Two types of storage are available:
- **Block Storage Legacy** - With this type, your storage is decoupled from your compute resources. You can increase your storage space without changing your node type. You can define your storage capacity by entering the desired amount in the box. The volume can be increased up to 10 TB.

- **Block Storage**: This storage type works like the [Block Storage Legacy](/managed-databases-for-postgresql-and-mysql/concepts/#block-storage-legacy), while providing lower latency and high resiliency through 5k IOPS. You can increase your volume to up to 10 TB.
- **Block Storage**: This storage type works like Block Storage Legacy, while providing lower latency and high resiliency through 5k or 15k IOPS. You can increase your volume to up to 10 TB.

- **Local SSD Storage** - Your storage is fixed and tied to your compute resource.
<Message type="note">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Managed Database for Redis™<sup>*</sup> is a low-latency caching solution base
- Select a node type.
4. Configure your Network. You can select either:

- **Private Network**: allows your databases to communicate in an isolated and secure network without requiring a public IP address. If you select this option, you must either:
- **Attach to Private Network**: allows your databases to communicate in an isolated and secure network without requiring a public IP address. If you select this option, you must either:
- select an existing Private Network to attach from the drop-down or
- create and attach a new one

Expand All @@ -48,7 +48,7 @@ Managed Database for Redis™<sup>*</sup> is a low-latency caching solution base
- Managed Databases for Redis™ are currently not compatible with the [Static NAT](/public-gateways/concepts/#nat) feature of [Scaleway Public Gateways](/public-gateways/concepts/#public-gateway). You can use Public Gateways in [SSH bastion](/public-gateways/how-to/use-ssh-bastion/) mode and perform port forwarding.
</Message>

- **Public network**: resources in a public network are publicly visible by default. The default Access Control List (ACL) settings allow anybody to connect to resources in your network. You can restrict access by configuring ACLs.
- **Set up public connectivity**: resources in a public network are publicly visible by default. The default Access Control List (ACL) settings allow anybody to connect to resources in your network. You can restrict access by configuring ACLs.
5. Complete the remaining steps in the creation wizard:
- Create credentials: add a name and set a password for your user.
<Message type="important">
Expand Down
169 changes: 107 additions & 62 deletions pages/managed-mongodb-databases/how-to/connect-database-instance.mdx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
---
meta:
title: How to connect to a MongoDB® Database Instance
title: How to connect to a Managed MongoDB® Database Instance
description: This page explains how to connect to a MongoDB® Database Instance
content:
h1: How to connect to a MongoDB® Database Instance
h1: How to connect to a Managed MongoDB® Database Instance
paragraph: This page explains how to connect to a MongoDB® Database Instance
tags: mongodb mongodb document database-instance managed-database database
dates:
validation: 2024-09-18
validation: 2024-02-17
posted: 2024-09-18
categories:
- managed-databases
Expand All @@ -19,7 +19,6 @@ Managed MongoDB® is currently in public beta. Click [here](https://www.scaleway

<Macro id="requirements" />


- A Scaleway account logged into the [console](https://console.scaleway.com)
- [Owner](/iam/concepts/#owner) status or [IAM permissions](/iam/concepts/#permission) allowing you to perform actions in the intended Organization
- A [MongoDB® Database Instance](/managed-mongodb-databases/quickstart/)
Expand All @@ -38,7 +37,7 @@ Managed MongoDB® is currently in public beta. Click [here](https://www.scaleway

Find below a detailed description of each connection mode:

### mongosh
### With mongosh

To connect to a public endpoint using the MongoDB® shell:

Expand Down Expand Up @@ -67,19 +66,11 @@ If the connection is successful, you should see the following message display on
rs-{db-instance-id} [primary] test>
```

Follow the same procedure to connect to a private endpoint for one node, replacing `{privateNetworkId}` with the `ID` of your Private Network:

```sh
mongosh "mongodb://{db-instance-id}-0.{privateNetworkId}" -u {username} --tlsCAFile {your_certificate.pem}
```

For multiple nodes, replace `{db-instance-id}` with the Database Instance UUID of each respective Instance, and `{privateNetworkId}` with the `ID` of your Private Network:

```sh
"mongodb://{db-instance-id}-0.{privateNetworkId},{db-instance-id}-1.{privateNetworkId},{db-instance-id}-2.{privateNetworkId}" -u {username} --tlsCAFile {your_certificate.pem}
```
<Message type="important">
To connect to a MongoDB® via a Private Network, use the following command: `mongosh "mongodb+srv://{username}:{password}@{instance_id}.{private_network_id}.internal/?tls=true&tlsCAFile={tls_certificate}"`. Make sure you replace the variables indicated within the `{}` with their corresponding values.
</Message>

### Python
### With Pymongo

The following code shows you how to use the `pymongo` library to connect using TLS.

Expand Down Expand Up @@ -115,8 +106,11 @@ documents = collection.find({})
for doc in documents:
print(doc)
```
<Message type="important">
To connect to a MongoDB® via a Private Network, use the following connection string: `connection_string = f"mongodb+srv://{username}:{password}@{instance_id}.{private_network_id}.internal/?tls=true&tlsCAFile={tls_certificate}"`. Make sure you replace the variables indicated within the `{}` with their corresponding values.
</Message>

### Node.js
### With Node.js

The following code shows you how to use the `mongodb` module to connect using TLS.

Expand All @@ -134,8 +128,10 @@ const databaseName = 'databaseName'
// Path to your TLS certificate file
const tlsCertificatePath = path.resolve(__dirname, 'path/to/your_tls_certificate.pem');

// Construct the connection string
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud`;
// Construct the public connection string
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud;`
// Construct the private connection string
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.${privateNetworkId}.internal;`

// Create a new MongoClient
const client = new MongoClient(connectionString, {
Expand Down Expand Up @@ -170,91 +166,140 @@ async function run() {
run().catch(console.dir);
```

### Go
### With Go

The following code shows you how to use the `mongo` driver to connect using TLS.
```go
package main

import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"

"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
// Replace with your MongoDB connection details
username := "your_username"
password := "your_password"
instanceID := "your_instance_id" // your instance_id
privateNetworkID := "your_private_network_id" // Id of your Private Network
region := "your_region" // the region of your database instance. "fr-par" for Paris.
tlsCertificate := "path/to/your_tls_certificate.pem" // path to your TLS certificate
databaseName = "databaseName"

// Read CA certificate
caCert, err := ioutil.ReadFile(tlsCertificate)
if err != nil {
log.Fatalf("Erreur lors de la lecture du fichier CA: %v", err)
}

username := "<replace_with_user_name>"
password := "<replace_with_password>"
host := "<endpoint ip>"
port := 1234 // replace with endpoint port number
caCertPath := "<instance_certificate.crt>"
// prepare the uri for the connection
uri := fmt.Sprintf(
"mongodb://%s:%s@%s:%d/rdb?tls=true&tlsCACert=%s&authMechanism=PLAIN",
username,
password,
host,
port,
caCertPath,
)
ctx := context.Background()
// connect to the database
client, _ := mongo.Connect(ctx, options.Client().ApplyURI(uri))
// get the database
db := client.Database("rdb")
// get the collection
cars := db.Collection("cars")
// insert a document
carToInsert := Car{Name: "Supercar", Year: 2020}
cars.InsertOne(ctx, carToInsert)

// read the document
carToRead := Car{}
cars.FindOne(ctx, map[string]interface{}{"name": "Supercar"}).Decode(&carToRead)

// print the document
fmt.Println(carToRead)
// Create certificate pool
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)

}
tlsConfig := &tls.Config{
RootCAs: caCertPool,
}

// Construct the public connection string
connectionString := fmt.Sprintf("mongodb+srv://%s:%s@%s.mgdb.%s.scw.cloud", username, password, instanceID, region)
// Construct the private connection string
connectionString := fmt.Sprintf("mongodb+srv://%s:%s@%s.%s.internal", username, password, instanceID, privateNetworkID)

// Create a new client and connect to the server
clientOptions := options.Client().
ApplyURI(connectionString).
SetTLSConfig(tlsConfig)
client, err := mongo.Connect(context.TODO(), clientOptions)

type Car struct {
Name string
Year int
if err != nil {
log.Fatal(err)
}

// Check the connection
err = client.Ping(context.TODO(), nil)

if err != nil {
log.Fatal(err)
}

fmt.Println("Connected to MongoDB!")

// Access a specific collection
collection := client.Database(databaseName).Collection("your_collection_name")

// Example: Find documents in the collection
cursor, err := collection.Find(context.TODO(), map[string]interface{}{})

if err != nil {
log.Fatal(err)
}

defer cursor.Close(context.TODO())

for cursor.Next(context.TODO()) {
var result map[string]interface{}
err := cursor.Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}

if err := cursor.Err(); err != nil {
log.Fatal(err)
}

// Close the connection once no longer needed
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}

fmt.Println("Connection to MongoDB closed.")
}
```

### Mongoose
### With Mongoose

The following code shows you how to use the `Mongoose` schema to connect using TLS.

```js
const mongoose = require('mongoose');
const path = require('path');

// Replace with your MongoDB® connection details
// Replace with your MongoDB connection details
const username = encodeURIComponent('your_username');
const password = encodeURIComponent('your_password');
const region = "your_region" // "fr-par" for Paris.
const region = "your_region"; // "fr-par" for Paris.
const instanceId = 'your_instance_id'; // your instance id
const privateNetworkId = 'your_private_network_id'; // your private network id
const databaseName = 'databaseName'

// Path to your TLS certificate file
const tlsCertificatePath = path.resolve(__dirname, 'path/to/your_tls_certificate.pem');

// Construct the connection string
// Construct the public connection string
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud`;
// Construct the private connection string
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.${privateNetworkId}.internal`;

// Connect to MongoDB® using Mongoose
// Connect to MongoDB using Mongoose
mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
tls: true, // Enable TLS/SSL
tlsCAFile: tlsCertificatePath, // Path to the CA certificate file
})
.then(() => {
console.log('Connected to MongoDB® with Mongoose!');
console.log('Connected to MongoDB with Mongoose!');
})
.catch(err => {
console.error('Connection error', err);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
meta:
title: How to connect an existing MongoDB® Database Instance to a Private Network
description: Instructions for connecting your MongoDB® Database Instance over a Private Network.
content:
h1: How to connect an existing MongoDB® Database Instance to a Private Network
paragraph: Instructions for connecting your MongoDB® Database Instance over a Private Network.
tags: managed-mongodb mongodb private-network database-instance
dates:
validation: 2025-02-17
posted: 2025-02-17
categories:
- managed-databases
- mongodb
---

[Private Networks](/vpc/concepts/#private-networks) allows you to enhance the security of your system's architecture by isolating it from the internet.

Using Private Networks improves performance by reducing the latency between your application and your database nodes. It also increases the security of your databases, as Instances in your Private Network can directly communicate with your Database Instance, without passing through the public internet.

You can [create new Database Instances](/managed-mongodb-databases/how-to/create-a-database-instance) to attach to your Private Network, or attach existing ones.

<Macro id="requirements" />

- A Scaleway account logged into the [console](https://console.scaleway.com)
- [Owner](/iam/concepts/#owner) status or [IAM permissions](/iam/concepts/#permission) allowing you to perform actions in the intended Organization
- A valid [API key](/iam/how-to/create-api-keys/)
- A [Managed MongoDB® Database Instance](/managed-mongodb-databases/how-to/create-a-database-instance)

## How to attach a Database Instance to a Private Network

<Message type="note">
You can only attach your Database Instance to one Private Network at a time.
</Message>

1. Click **MongoDB®** under **Managed Databases** on the side menu. A list of your Database Instances displays.
2. Click the database name or <Icon name="more" />, then click **More info** to access the Database Instance information page.
3. Scroll to the **Network** section.
4. Click **Attach Private Network** next to **Private endpoint**. A pop-up appears.
5. Choose one or both of the options below:
- Select and attach an existing Private Network and select the network from the drop-down list.
<Message type="important">
The Database Instance must be attached to a Private Network in the same region.
</Message>
- Create and attach a new Private Network and enter the name of the network in the form.
<Message type="important">
If you select this option, a Private Network with default settings will be created in the same region as your Database Instance. Do not use a TLD (e.g. `dev` or `cloud`) as a name, to avoid conflicts.
</Message>
6. Click **Attach to Private Network** to conclude.

<Message type="note">
Managed MongoDB® is currently not compatible with the [Static NAT](/public-gateways/concepts/#nat) feature of [Scaleway Public Gateways](/public-gateways/concepts/#public-gateway). You can use Public Gateways in [SSH bastion](/public-gateways/how-to/use-ssh-bastion/) mode and perform port forwarding.
</Message>

<Message type="tip">
Once you have attached your Database Instance to a Private Network, you can [connect to the Database Instance](/managed-mongodb-databases/how-to/connect-database-instance) using the private endpoint connection string.
</Message>

## How to detach a Database Instance from a Private Network

1. Click **MongoDB®** under **Managed Databases** on the side menu. A list of your Database Instances displays.
2. Click the database name or <Icon name="more" />, then click **More info** to access the Database Instance information page.
3. Scroll to the **Network** section.
4. Click **Detach Private Network**. A pop-up appears.
5. Click **Detach resource** to confirm.

<Message type="note">
This action takes a few moments to complete. During this time, your Database Instance:
- remains available,
- goes into **Configuring** mode, and
- network configuration actions become unavailable
</Message>
Loading
Loading