Best practices for accessing ApsaraDB for MongoDB
In Function Compute, each execution instance is stateless and does not share data with other instances. You can use a database to persist structured data and share state. By connecting Function Compute to a cloud database, you can query and insert data. This topic uses a Python function to demonstrate how to access an ApsaraDB for MongoDB instance from within the same VPC or across different VPCs and regions.
Prerequisites
-
Create an ApsaraDB for MongoDB instance. This topic uses a sharded cluster instance as an example. For more information about instance types, see standalone instance, replica set instance, and sharded cluster instance.
-
The sample code in
app.pyinserts a document into the collection namedfc_colin the database namedtest-db. You can modify the database and collection names as needed. For more information, see Write data.
Procedure
Step 1: Configure the database whitelist
Scenario 1: Access a MongoDB database within the same VPC
If you access a database in the same VPC, ensure that the database instance and the function are in the same region. We recommend that you create the database instance in a zone that Function Compute supports. For more information, see Zones that Function Compute supports. If your database instance is not in a supported zone, you can create a vSwitch in the same zone as your function and specify its ID in the function's VPC configuration. Because vSwitches in the same VPC can communicate with each other over the private network, your function can use this vSwitch to access resources in other zones of the VPC. For more information, see What do I do if I receive the 'vSwitch is in unsupported zone' error?.
-
Log on to the Function Compute console and create a Python Web function. On the function details page, click the Configuration tab. In the Advanced Settings section, click Modify. In the Advanced Settings panel, locate the Network section, enable VPC access for the function, and configure the target VPC resources.
NoteMake sure that the VPC you configure for the function is the same as the VPC bound to the database instance.
You must select three resources: a VPC, a vSwitch, and a security group. We recommend that you configure vSwitches in two or more availability zones to leverage the multi-AZ disaster recovery feature of Function Compute.
-
On the function details page, click the Configuration tab. In the Network section, obtain the CIDR block of the vSwitch configured for the function.
-
Add the vSwitch CIDR block to the database whitelist.
ImportantYou must use an IP address whitelist to authorize function access to the database. Do not use a security group. Otherwise, the function may occasionally fail to connect to the database and disrupt your services.
-
Log on to the ApsaraDB for MongoDB console. In the left-side navigation pane, click Sharded Cluster Instances, and then click the ID of the target instance.
-
On the instance details page, in the left-side navigation pane, choose .
-
Click Manually Modify to the right of the default group. In the Manually Modify panel, add the vSwitch CIDR block to the whitelist, and then click OK.
In the Allowed IP Addresses field, enter the IPv4 CIDR block, for example,
192.168.xxx.xxx/24.
After the configuration is complete, the function can access the MongoDB database via its private IP address.
-
Scenario 2: Access a MongoDB database across VPCs or regions
VPCs and regions are logically isolated. By default, you cannot access a database across VPCs or regions. To enable this, configure a static public IP address for your function. The system creates a public NAT gateway in the function's VPC, which allows the function to access the database over the internet by using the public IP address.
-
Log on to the Function Compute console. In the left-side navigation pane, click Functions. Select a region and then create a function as prompted.
-
On the function details page, click the Configuration tab. In the Advanced Settings section, click Modify. In the Network section of the Advanced Settings panel, turn on the Static Public IP Address switch and turn off the Allow Default NIC to Access Internet switch to activate the fixed public IP. Then, click Deploy.
-
On the function details page, click the Configuration tab. In the Network section, obtain the elastic IP address that is configured for the function.
-
Add the function's fixed public IP address to the database whitelist.
ImportantYou must use an IP address whitelist to authorize function access to the database. Do not use a security group. Otherwise, the function may occasionally fail to connect to the database and disrupt your services.
-
Log on to the ApsaraDB for MongoDB console. In the left-side navigation pane, click Sharded Cluster Instances, and then click the ID of the target instance.
-
On the instance details page, in the left-side navigation pane, choose .
-
Click Manually Modify to the right of the default group. In the Manually Modify panel, add the IPv4 address to the whitelist, and then click OK.
The whitelist supports formats such as a single IP address (for example,
192.168.0.1) and a CIDR block (for example,192.168.0.0/24). Separate multiple IP addresses with commas. Entering0.0.0.0/0allows access from any IP address but poses a high security risk.
After you complete the configuration, the function can access the MongoDB database through its public endpoint.
-
Step 2: Access ApsaraDB for MongoDB
-
Log on to the Function Compute console. In the function list, find the target function. On the function details page, click the Code tab and enter the following sample code in the code editor.
from flask import Flask import os from pymongo import MongoClient app = Flask(__name__) # Global variable for the singleton MongoDB client. _mongo_client = None # Create a database connection (singleton pattern). def getConnection(): global _mongo_client try: # If a connection exists and is active, return it. if _mongo_client is not None: try: # Check if the connection is valid (using a simple command). _mongo_client.admin.command('ping') # Use the ping command on the admin database to test the connection status. return _mongo_client except Exception: # If the connection is lost, reset it. _mongo_client = None # If no connection exists or the connection is lost, create a new one. url = os.environ['MONGO_URL'] _mongo_client = MongoClient(url) return _mongo_client except Exception as e: print(f"ERROR: Failed to connect to MongoDB instance: {e}") raise @app.route('/', defaults={'path': ''}) @app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE']) def hello_world(path): dbName = os.environ['MONGO_DATABASE'] # Get the MongoDB connection. client = getConnection() # Operate on the collection. Change 'fc_col' to your actual collection name. col = client[dbName]['fc_col'] col.insert_one(dict(DEMO="FC", MSG="Hello FunctionCompute For MongoDB")) doc = col.find_one(dict(DEMO="FC")) print('find documents:' + str(doc)) return str(doc) if __name__ == '__main__': app.run(host='0.0.0.0', port=9000) -
On the Code tab, in the WebIDE interface, choose to open a terminal window. Run the following command to install the
pymongolibrary.pip install -t . pymongo -
On the function details page, click the Configuration tab. In the Advanced Settings section, click Modify. In the Advanced Settings panel, locate the Environment Variables section. Configure the following environment variables, and then click Deploy.
Parameter
Value
Description
MONGO_DATABASE
test-db
The name of the database created in the MongoDB database instance.
NoteUse a manually created database. If you use the root account, MongoDB 7.0.4 and later versions do not grant write permissions on the default admin database.
MONGO_URL
mongodb://root:password@s-bp132a4e334e**.mongodb.rds.aliyuncs.com:3717,s-bp1b486e9aa4**.mongodb.rds.aliyuncs.com:3717
The access address of the MongoDB database instance.
-
For access within the same VPC, use the database's private endpoint.
-
For access across VPCs or regions, use the database's public endpoint.
Log on to the ApsaraDB for MongoDB console and click the target instance. In the left-side navigation pane of the instance details page, click Database Connection. On the Database Connection page, you can find the database's private and public endpoints.
-
-
On the function details page, select the Code tab and click Test Function. After the function is successfully executed, view the response. A record is successfully inserted into the MongoDB database.
The result is a MongoDB document:
{'_id': ObjectId('xxx'), 'DEMO': 'FC', 'MSG': 'Hello FunctionCompute For MongoDB'}.
More information
-
For more sample code, see Accessing a MongoDB database by using Python in Function Compute.
-
If your database connection fails, troubleshoot the issue based on the symptoms. For more information, see Common causes of database connection failures.
-
To use the Serverless Devs command-line tool to create a function and access an ApsaraDB for MongoDB database, follow the steps below.