All Products
Search
Document Center

Function Compute:Best practices for accessing ApsaraDB for MongoDB

Last Updated:Dec 26, 2025

In Function Compute, states are not shared between execution environment instances. You can use a database to persist structured data to enable state sharing. By accessing a cloud database from Function Compute, you can perform operations such as data queries and insertions. This topic uses a Python function as an example to describe how to access ApsaraDB for MongoDB from the same VPC or from different VPCs and regions.

Prerequisites

Procedure

Step 1: Configure the database whitelist

Scenario 1: Access an ApsaraDB for MongoDB database in the same VPC

If you choose to access a database in the same VPC, make sure 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 zone that is supported by Function Compute, you can create a vSwitch in your VPC in the same zone as Function Compute and use this vSwitch ID in the VPC configurations of the function. vSwitches in the same VPC can communicate with each other over the private network. Therefore, Function Compute can use the vSwitch to access resources in VPCs that reside in other zones. For more information, see What do I do if the vSwitch is in unsupported zone error occurs?.

  1. Log on to the Function Compute console. Then, create a Python web function, enable VPC access for the function, and configure the target VPC resources.

    Note

    Make sure the VPC configured for the function is the same as the VPC to which the database instance is attached.

    image

  2. On the function details page, navigate to the Configuration > Network tab. On the Network tab, obtain the vSwitch CIDR block from the function configuration.

    image

  3. Add the vSwitch CIDR block obtained in the previous step to the database access whitelist.

    Important

    Use an IP address whitelist to grant the function access to the database. Do not use security groups. Otherwise, the function may occasionally fail to connect to the database, which can affect your business.

    1. Log on to the ApsaraDB for MongoDB console. In the navigation pane on the left, choose Sharded Cluster Instances and click the ID of the target instance.

    2. On the instance details page, in the navigation pane on the left, choose Data Security > Whitelist Settings.

    3. Click Manually Modify to the right of the default group. In the Manually Modify panel, add the vSwitch IPv4 CIDR block to the whitelist, and then click OK.

      image

    After the configuration is complete, the function can access the ApsaraDB for MongoDB database using the private endpoint of the database.

Scenario 2: Access an ApsaraDB for MongoDB database across VPCs or regions

Different VPCs and regions are completely logically isolated from each other. In general, you cannot access databases across VPCs and regions. If you need to access a database across VPCs or regions, you can configure a static public IP address for the function. In this case, the system creates a public NAT gateway in the VPC to which the function is attached. You can use the public gateway to access the database through the public IP address.

  1. Log on to the Function Compute console. In the navigation pane on the left, choose Functions, select a region, and then follow the prompts to create a function.

  2. On the function details page, navigate to the Configuration > Network tab. On the Network tab, configure a static public IP address for the function, and then click Deploy.

    image

  3. In the Static Public IP Configuration dialog box, select the checkbox and click OK. After the configuration is complete, set Allow functions to access the Internet through the default network interface card to No to activate the static public IP address.

  4. On the function details page, navigate to the Configuration > Network tab. On the Network tab, obtain the static public IP address configured for the function.

    image

  5. Add the static public IP address obtained in the previous step to the database access whitelist.

    Important

    Use an IP address whitelist to grant the function access to the database. Do not use security groups. Otherwise, the function may occasionally fail to connect to the database, which can affect your business.

    1. Log on to the ApsaraDB for MongoDB console. In the navigation pane on the left, choose Sharded Cluster Instances and click the ID of the target instance.

    2. On the instance details page, in the navigation pane on the left, choose Data Security > Whitelist Settings.

    3. Click Manual Modification to the right of the default group. In the Manual Modification panel, add the vSwitch IPv4 CIDR block to the whitelist and click OK.

      image

    After the configuration is complete, the function can access the ApsaraDB for MongoDB database using the public endpoint of the database.

Step 2: Access ApsaraDB for MongoDB from the function

  1. Log on to the Function Compute console. In the function list, find the target function. On the function details page, click the Code tab. In the code editor, add the following sample code.

    from flask import Flask
    import os
    from pymongo import MongoClient
    
    app = Flask(__name__)
    
    # Use a global variable to store the MongoDB singleton connection.
    _mongo_client = None
    
    # Create a database connection (singleton pattern).
    def getConnection():
        global _mongo_client
        try:
            # If the connection already exists and is not disconnected, return it directly.
            if _mongo_client is not None:
                try:
                    # Test if the connection is valid.
                    _mongo_client.admin.command('ping')  # Use the ping command of the admin database to test the connection status.
                    return _mongo_client
                except Exception:
                    # If the connection is disconnected, reset it.
                    _mongo_client = None
    
            # If the connection does not exist or is disconnected, 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 as needed.
        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)
    
    
  2. On the Code tab, in the WebIDE interface, choose Terminal > New Terminal. In the terminal window, run the following command to install the `pymongo` library.

    pip install -t . pymongo
  3. On the function details page, navigate to the Configuration > Environment Variables tab. Click Edit. In the Environment Variables panel, configure the following environment variables.

    Environment Variable Name

    Environment Variable Value

    Description

    MONGO_DATABASE

    test-db

    The name of the database created in the ApsaraDB for MongoDB instance.

    Note

    If you use the root account, versions later than MongoDB 7.0.4 do not have write permissions on the default `admin` database. We recommend that you use a manually created database.

    MONGO_URL

    mongodb://root:password@s-bp132a4e334e****.mongodb.rds.aliyuncs.com:3717,s-bp1b486e9aa4****.mongodb.rds.aliyuncs.com:3717

    The endpoint of the ApsaraDB for MongoDB instance.

    • If you chose to access the database within the same VPC, set this environment variable to the private endpoint of the database.

    • If you chose to access the database across VPCs or regions, set this environment variable to the public endpoint of the database.

    Log on to the ApsaraDB for MongoDB console and click the target instance. In the navigation pane on the left of the instance details page, choose Database Connection. On the Database Connection page, obtain the private or public endpoint of the database.

  4. On the function details page, navigate to the Code tab and click Test Function. After the function is executed, view the returned result. The following figure shows that a data record is successfully inserted into the ApsaraDB for MongoDB database.

    image

More information

  • For more sample code for accessing an ApsaraDB for MongoDB database, see Python code for accessing an ApsaraDB for MongoDB database from Function Compute.

  • If you cannot access the database, troubleshoot the issue based on the symptoms. For more information, see Common causes of database access failures.

  • Follow these steps to create a function and access an RDS MySQL database using the Serverless Devs command line interface.

    Click to view the steps for Serverless Devs

    1. Install Serverless Devs and Docker, and configure your AccessKey pair. For more information, see Quick Start.

    2. Create a code directory named mycode. Create the s.yaml file and the app.py file. For the sample code for app.py, see the code provided in Step 2: Accessing ApsaraDB for MongoDB from the function. The following code is an example of the s.yaml file.

      The following s.yaml example is for the scenario of accessing an ApsaraDB for MongoDB database in the same VPC. To access the database across VPCs or regions, see Scenario 2: Accessing an ApsaraDB for MongoDB database across VPCs or regions.

      # ------------------------------------
      #   Official documentation: https://manual.serverless-devs.com/user-guide/aliyun/#fc3
      #   Common tips: https://manual.serverless-devs.com/user-guide/tips/
      #   If you have questions, join the DingTalk group: 33947367
      # ------------------------------------
      edition: 3.0.0
      name: hello-world-app
      access: "default"
      
      vars: # Global variables
        region: "cn-hangzhou"  # If you access an ApsaraDB for MongoDB database in the same VPC, make sure the function is deployed in the same region as the database.
      
      resources:
        hello_world:
          component: fc3 
          actions:       
            pre-${regex('deploy|local')}: 
              - component: fc3 build 
          props:
            region: ${vars.region}              
            functionName: "start-python-0t1m"
            runtime: custom.debian10
            description: 'hello world by serverless devs'
            timeout: 10
            memorySize: 512
            cpu: 0.5
            diskSize: 512
            code: ./code
            customRuntimeConfig:
              port: 9000
              command:
                - python3
                - app.py
            internetAccess: true
            vpcConfig:
             vpcId: vpc-bp1dxqii29fpkc8pw**** # The ID of the VPC where the database instance is located.
             securityGroupId: sg-bp12ly2ie92ixrfc**** # The security group ID.
             vSwitchIds: 
              - vsw-bp1ty76ijntee9z83**** # Make sure that the CIDR block of this vSwitch is added to the access whitelist of the database instance.
            environmentVariables:
              PYTHONPATH: /code/python
              PATH: /code/python/bin:/var/fc/lang/python3.10/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin
              MONGO_DATABASE: test-db # The database name.
              MONGO_URL: mongodb://username:password@d-bp1b05cac9df0dd****.mongodb.rds.aliyuncs.com:37**  # The database endpoint. The username and password are the credentials for connecting to the database. If the username or password contains special characters, you must escape them according to RFC 3986.
             
    3. Run the following command to build the project.

      sudo s build --use-docker
    4. Run the following command to deploy the project.

      sudo s deploy -y
    5. Run the following command to invoke the function.

      Note

      Ensure that the vSwitch CIDR block or static public IP address for the function is added to the database instance's access whitelist. For more information, see Step 3.

      sudo s invoke -e "{}"