Best practices for accessing RDS PostgreSQL

Updated at:

In Function Compute, states are not shared between different execution environment instances. You can use databases to persist structured data to achieve state sharing. Through Function Compute, you can access cloud databases to perform operations such as data queries and data insertion. This topic uses Python 3 as an example to describe how to access ApsaraDB RDS for PostgreSQL within the same VPC or across VPCs and regions.

Before you start

  • Quickly create an RDS PostgreSQL instance

  • The logic in the index.py sample code in this topic is to query all data in a database table named users. You can modify the table name according to your actual situation and ensure that there is at least one record in the table.

Procedure

Step 1: Set up database whitelist

Scenario 1: Access PostgreSQL database within the same VPC

Important
  • Make sure that the database instance that you create is in the same region as the function that needs to access the database instance.

  • You create a database instance in a zone that is supported by Function Compute. For more information, see Zones supported by Function Compute.

  • If your database instance is not deployed in a zone that is supported by Function Compute, create a vSwitch in your VPC. The vSwitch must be in the same zone as Function Compute. In addition, you must specify the vSwitch ID in the VPC configuration of the specified service in Function Compute. Because different vSwitches within the same VPC can communicate with each other through the internal network, Function Compute can access resources in other zones within the VPC through this vSwitch. For specific steps, see What should I do if I encounter the "vSwitch is in unsupported zone" error?.

  1. Go to the RDS instance list. Select a region, click the target instance ID, and navigate to the Basic Information page. Click View Connection Details next to VPC to find the private network details for your PostgreSQL instance.

  2. Log in to the Function Compute console and create a Python Web function. On the function's details page, go to the Configuration tab. Under Advanced Settings, click Modify. In the Advanced Settings panel, go to the Network section, enable VPC access, and configure the required VPC resources.

    Note

    Make sure that the VPC configured for the function is the same as the VPC bound to the database instance.

    Specifically, you must configure the following three items: VPC, vSwitch, and security group. For high availability, we recommend selecting vSwitches in at least two zones to leverage the multi-zone disaster recovery capabilities of Function Compute. Accessing a vSwitch across zones may add 1 ms to 2 ms of latency.

  3. On the function details page, select the Configuration tab. In the Network section, find the CIDR block of the vSwitch configured for your function.

  4. Add the CIDR block of the vSwitch obtained in the previous step to the access whitelist.

    Important

    Use an IP address whitelist to authorize functions to access the database. Do not use the security group mode. Otherwise, functions may occasionally fail to connect to the database, which affects the businesses.

    1. Log on to the RDS Management Console, select a region at the top, and then click the target instance ID.

    2. In the left-side navigation pane, choose Whitelist and SecGroup. On the Whitelist Settings tab, find the target whitelist group and click Modify in the Actions column.

    3. In the Edit Whitelist panel, enter the vSwitch CIDR block in the IP Addresses: field and click OK.

After the configuration is complete, the function can access the PostgreSQL database through the internal network address of the database.

Scenario 2: Access PostgreSQL database across VPCs or regions

Different VPCs and regions are completely logically isolated from each other. Under normal circumstances, databases cannot be accessed 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. The system will create a public NAT Gateway in the VPC bound to the function, allowing access to the database through the public IP address.

  1. Go to the RDS instance list. Select a region, click the target instance ID, and navigate to the Basic Information page. Click View Connection Details next to VPC to find the connection details for your PostgreSQL instance.

  2. Log in to the Function Compute console and create a Python Web function. On the Configuration tab, find Advanced Settings and click Modify. In the Advanced Settings panel, locate the Network section. Turn on the Static Public IP Address switch and turn off the Allow Default NIC to Access Internet switch to activate the static IP. Then, click Deploy.

  3. On the function details page, select the Configuration tab. In the Network section, get the static public IP address assigned to the function.

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

    Important

    Use an IP address whitelist to authorize functions to access the database. Do not use the security group mode. Otherwise, functions may occasionally fail to connect to the database, which affects the businesses.

    1. Log on to the RDS Management Console, select a region at the top, and then click the target instance ID.

    2. In the left-side navigation pane, choose Whitelist and SecGroup. On the Whitelist Settings tab, find the target whitelist group and click Modify in the Actions column.

    3. In the Edit Whitelist panel, enter the static public IP address in the IP Addresses: field and click OK.

After the configuration is complete, the function can access the PostgreSQL database through the public network address of the database.

Step 2: Access PostgreSQL database in the function

  1. Log in to the Function Compute console. Find your function, go to the function details page, and click the Code tab. Enter the following sample code into the editor, modifying it as needed for your database table.

    from flask import Flask, jsonify
    import psycopg2  # The psycopg2 library must be installed.
    import os
    import sys
    from datetime import datetime
    import logging
    app = Flask(__name__)
    # A global variable to store a reusable PostgreSQL connection.
    _postgresql_connection = None
    # Creates a singleton database connection.
    def getConnection():
        global _postgresql_connection
        try:
            # If a connection exists and is active, reuse it.
            if _postgresql_connection is not None:
                try:
                    # Check if the connection is still valid.
                    with _postgresql_connection.cursor() as cursor:
                        cursor.execute("SELECT 1")  # A simple query to test the connection status.
                        result = cursor.fetchone()
                        if result and result[0] == 1:
                            return _postgresql_connection
                except psycopg2.OperationalError:
                    # Reset the connection if it is broken.
                    _postgresql_connection = None
            # If no connection exists or the existing one was broken, create a new one.
            _postgresql_connection = psycopg2.connect(
                database=os.environ['DATABASE'],
                user=os.environ['USER'],
                password=os.environ['PASSWORD'],
                host=os.environ['HOST'],
                port=os.environ['PORT'],
            )
            return _postgresql_connection
        except Exception as e:
            print(f"ERROR: Unexpected error: Could not connect to PostgreSQL instance: {e}")
            raise
    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
    def hello_world(path):
        conn = getConnection()
        try:
            with conn.cursor() as cursor:
                # Query all records from the 'users' table. Change 'users' to your actual table name.
                sql = "SELECT * FROM users"
                cursor.execute(sql)
                result = cursor.fetchall()
                columns = [desc[0] for desc in cursor.description]  # Get a list of column names.
                # Convert the query result into a list of dictionaries.
                users = []
                for row in result:
                    user = {}
                    for idx, column_name in enumerate(columns):
                        value = row[idx]
                        if isinstance(value, datetime):  # Handle datetime fields.
                            user[column_name] = value.strftime('%Y-%m-%d %H:%M:%S')
                        else:
                            user[column_name] = value
                    users.append(user)
                if users:
                    # Return a JSON response with all users.
                    return jsonify(users), 200
                else:
                    # Return a 404 error if no users are found.
                    return jsonify({'error': 'No users found'}), 404
        except Exception as e:
            logging.error(f"Error occurred during database operation: {e}")
            return jsonify({'error': 'Database error'}), 500
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=9000)
    
  2. Run the pip3 install -t . psycopg2 command to install the required dependencies, and then click Deploy to apply the dependencies. For detailed steps, see Install dependencies by using the terminal in the Web IDE.

  3. On the Function Details tab, under Advanced Settings, click Modify. In the advanced configuration panel, go to the Environment Variables section, configure the following environment variables, and then click Deploy.

    Environment Variable Name

    Environment Variable Value

    Description

    HOST

    pgm-*****q.pg.rds.aliyuncs.com

    The access address of the database instance. If you choose the PostgreSQL database within the same VPC scenario, set this environment variable value to the internal network address of the database. If you choose the Access PostgreSQL database across VPCs or regions scenario, set this environment variable value to the external network address of the database.

    Go to the Instance List page, select a region at the top, and then click the ID of the target instance. In the left-side navigation pane, click Database Connection, and in the Database Connection section, obtain the connection address information.

    PORT

    5432

    Database internal network port number

    USER

    *****

    The account name created in the PostgreSQL instance.

    PASSWORD

    *****

    Database Password

    DATABASE

    *****

    The database name created in the instance.

  4. On the function details page, select the Code tab, click Test Function, and view the return result after successful execution.

    A successful result is a JSON array of database records, such as [{"age": 25, "create_date": "2025-04-17 14:08:46", "id": 1, "name": "Alice"}]. This confirms that the function successfully connected to the PostgreSQL database and retrieved data.

More information

  • For more examples of accessing RDS PostgreSQL databases, see Function Compute Python accessing PostgreSQL database.

  • For information about how to view the vSwitch information configured for Function Compute and how to allow the vSwitch CIDR block of Function Compute in the RDS MySQL database, see Configure network and Configure a whitelist for PostgreSQL respectively.

  • If database access fails, you need to troubleshoot based on the problem symptoms. For details, see Common causes of database access failure.

  • If you want to use the Serverless Devs command-line tool to create functions and access ApsaraDB RDS for PostgreSQL databases, see the following steps.

    Click here to view Serverless Devs operation steps

    1. Install Serverless Devs and Docker, and add credential information. For specific operations, see Quick Start.

    2. Create a code directory named mycode, and prepare an s.yaml file and a app.py code file. The sample code for app.py is provided in Step 2: Access a PostgreSQL database from a function. The following provides a sample s.yaml file.

      The following s.yaml example is for accessing a PostgreSQL database within the same VPC. If you need to access the database across VPCs or regions, see Scenario 2: Accessing a PostgreSQL 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 connecting within the same VPC, ensure the function is in the same region as the RDS database.
      resources:
        hello_world:
          component: fc3 
          actions:       
            pre-${regex('deploy|local')}: 
              - component: fc3 build 
          props:
            region: ${vars.region}              
            functionName: "start-python-PostgreSQL"
            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 VPC ID of your database instance.
              securityGroupId: sg-bp12ly2ie92ixrfc**** # The security group ID.
              vSwitchIds: 
                 - vsw-bp1ty76ijntee9z83**** # Ensure the CIDR block of this vSwitch is in the database's access whitelist.
            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
              HOST: pgm-*****.pg.rds.aliyuncs.com  # The database endpoint.
              USER: ******   # The account username created in the instance.
              PASSWORD: *****     # The database password.
              DATABASE: *****     # The name of the database created in the instance.
              PORT: "5432"        # The database port.
              

      The directory structure of the code is as follows.

      ├── code
      │ ├── app.py
      │ └── requirements.txt
      └── s.yaml

      The dependencies specified in the requirements.txt file are shown below.

      flask==2.2.5
      psycopg2==2.9.10
    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

      Make sure that the CIDR block of the vSwitch configured for the function has been added to the database instance access whitelist. For specific operations, see Step 4.

      sudo s invoke -e "{}"