All Products
Search
Document Center

Elastic Container Instance:Configure an elastic container instance to connect to an ApsaraDB RDS instance

Last Updated:Mar 20, 2024

If you want to connect a containerized application to an ApsaraDB RDS instance, you must add the endpoint of the containerized application to the whitelist of the ApsaraDB RDS instance and specify the database connection information when you create an Elastic Container Instance-based pod. This topic describes how to connect a pod to an ApsaraDB RDS instance when you create the pod in a Container Service for Kubernetes (ACK) Serverless cluster. In this topic, an ApsaraDB RDS for MySQL instance is used.

Background information

ApsaraDB RDS is a stable, reliable, and scalable online database service. ApsaraDB RDS uses Apsara Distributed File System and the high-performance SSDs of Alibaba Cloud to support database engines, such as MySQL, SQL Server, and PostgreSQL. In this topic, an ApsaraDB RDS for MySQL instance is used as an example to explain how to connect an elastic container instance to an ApsaraDB RDS instance. You can select a database engine based on your business requirements. For more information, see the "Database engines" section of the Getting Started topic.

Prerequisites

  • An ApsaraDB RDS for MySQL instance is created, and a user account is created for the instance. For more information, see Create an ApsaraDB RDS for MySQL instance and Create databases and accounts for an ApsaraDB RDS for MySQL instance.

  • An ACK Serverless cluster is created. For more information, see Create an ACK Serverless cluster.

    Note

    In this example, an ACK Serverless cluster is used. If you use a Kubernetes cluster of another type, make sure that a virtual node is deployed in the cluster to connect to Elastic Container Instance.

  • Make sure that the ApsaraDB RDS instance and the Kubernetes cluster can communicate with each other.

    We recommend that you deploy the ApsaraDB RDS instance and the Kubernetes cluster in the same virtual private cloud (VPC). This way, the ApsaraDB RDS instance and the applications in the clusters are interconnected with each other over the VPC. If you deploy the instance and the cluster in different VPCs, you must enable Internet connectivity between the instance and the applications in the cluster.

Configure a whitelist for the ApsaraDB RDS instance and obtain the endpoint of the database.

Access the ApsaraDB RDS instance over a VPC

If the ApsaraDB RDS instance and the Kubernetes cluster are deployed in the same VPC, applications in the cluster can access the instance over the VPC. You must configure a whitelist for the ApsaraDB RDS instance and obtain the internal endpoint of the database.

  1. Configure a whitelist for the ApsaraDB RDS instance.

    When applications in the Kubernetes cluster access the ApsaraDB RDS instance over the internal network, you can add IP addresses or security groups to the whitelist:

  2. Obtain the internal endpoint of the database from the Database Connection page of the ApsaraDB RDS instance.

Access the ApsaraDB RDS instance over the Internet

If the ApsaraDB RDS instance and the ACK Serverless cluster are deployed in different VPCs, applications in the cluster must use the Internet to access the instance. You must configure a whitelist for the ApsaraDB RDS instance and obtain the public endpoint of the database. Procedures:

Important
  • If you use a public endpoint to access the ApsaraDB RDS instance, the security of the instance is compromised. Proceed with caution.

  • To accelerate and secure data transmission, we recommend that you migrate your applications from the ACK Serverless cluster to an elastic container instance that is deployed in the same region and has the same network type as the ApsaraDB RDS instance. This way, the applications can access the ApsaraDB RDS instance over the internal endpoint.

  1. Configure a whitelist for the ApsaraDB RDS instance.

    If applications access the instance over the Internet, you must configure an IP address whitelist for the instance. For more information, see Configure an IP address whitelist for an ApsaraDB RDS for MySQL instance.

    • If the elastic container instance uses an NAT gateway to access the Internet, you must add the EIP address that is associated with the NAT gateway to the IP address whitelist.

    • If the elastic container instance uses an EIP to access the Internet, you must add the EIP address that is associated with the elastic container instance to the IP address whitelist.

  2. Apply for and record the public endpoint of the database. For more information, see Apply for or release a public endpoint for an ApsaraDB RDS for MySQL instance.

Configure an application to connect to the ApsaraDB RDS instance

In this topic, a VPC is used to connect an application in an ACK Serverless cluster to the ApsaraDB RDS instance. Procedure:

  1. Log on to the ACK console.

  2. On the Clusters page, find the cluster that you want to manage and click the cluster name. The management page of the cluster appears.

  3. Create a ConfigMap to configure the connection to the ApsaraDB RDS instance.

    Note

    ConfigMap can decouple environment configurations from container images. This facilitates the modification of application configurations.

    1. In the left-side navigation pane, choose Configurations > ConfigMaps.

    2. Click Create in the upper-right corner of the page.

    3. Configure the ConfigMap and click OK.

      In the panel that appears, specify a name for the ConfigMap. Example: rds-config. Then, configure the parameters that are described in the following table.

      Parameter

      Example

      Description

      host

      rm-2zem97a62s9******.mysql.rds.aliyuncs.com

      The endpoint of the database. You can obtain the endpoint on the Database Connection page of the ApsaraDB RDS instance.

      port

      3306

      The port number of the database. You can obtain the port number on the Database Connection page of the ApsaraDB RDS instance.

      database

      test-db

      The name of the database. You can obtain the name of the database on the Databases page of the ApsaraDB RDS instance.

  4. Create a secret to add the username and password of the database.

    Note

    Secrets ensure that confidential information such as the username and password of the database can be securely passed to applications.

    1. In the left-side navigation pane, choose Configurations > Secrets.

    2. Click Create.

    3. Configure the secret and click OK.

      In the panel that appears, specify a name for the secret. Example: rds-secret. Then, configure the parameters that are described in the following table.

      Parameter

      Example

      Description

      username

      test

      The username that is used to access the database. You can obtain the username on the Accounts page of the ApsaraDB RDS instance.

      password

      pwd******

      The password that is used to access the database. If you forget your password, you can reset the password on the Accounts page.

  5. Create an Elastic Container Instance-based pod and test whether the pod can be connected to the ApsaraDB RDS instance.

    1. In the left-side navigation pane, choose Workloads > Pods.

    2. Click Create from YAML.

    3. Enter the content of the YAML file and click Create.

      ApsaraDB RDS for MySQL is fully compatible with open source MySQL. You can connect to an ApsaraDB RDS instance from a database client in the same manner that you connect to an open source MySQL database. The following code provides a sample configuration.

      Note

      If you use the sample configuration that is provided in this topic to test the database connection, create a table named username in the ApsaraDB RDS instance and add a column named user to the table.

      The following YAML code uses environment variables to pass in the database connection information, including the endpoint, port number, name, username, and password of the database. The image contains a Python script that can be used to connect the database to the cluster and insert data.

      apiVersion: v1
      kind: Pod
      metadata:
        labels:
          name: rds-test
        name: rds-test
      spec:
        containers:
        - name: test-rds
          image: registry.cn-hangzhou.aliyuncs.com/eci_open/sqlclient:1.0.1  # An image that contains a Python job that is used to connect the ApsaraDB RDS instance to the cluster.
          imagePullPolicy: IfNotPresent
          command: ["/bin/bash","-c","python3 /testapp/mysqlclient.py"]
          env:
          - name: MYSQL_HOST 
            valueFrom:
              configMapKeyRef:
                name: rds-config  # The name of the ConfigMap.
                key: host # The key in the ConfigMap.
          - name: MYSQL_PORT
            valueFrom:
              configMapKeyRef:
                name: rds-config # The name of the ConfigMap.
                key: port # The key in the ConfigMap.
          - name: MYSQL_DB
            valueFrom:
              configMapKeyRef:
                name: rds-config  # The name of the ConfigMap.
                key: database # The key in the ConfigMap.
          - name: MYSQL_USERNAME
            valueFrom:
              secretKeyRef:
                name: rds-secret # The name of the secret.
                key: username # The key in the secret.
          - name: MYSQL_PWD
            valueFrom:
              secretKeyRef:
                name: rds-secret # The name of the secret.
                key: password # The key in the secret.
        restartPolicy: Never

      The preceding image contains a Python script (mysqlclient.py) that can be used to insert data into the user column of the username table. Script content:

      import pymysql
      import os
      import time
      
      config = {
          'host': str(os.getenv('MYSQL_HOST')),
          'port': int(os.getenv('MYSQL_PORT')),
          'user': str(os.getenv('MYSQL_USERNAME')),
          'password': str(os.getenv('MYSQL_PWD')),
          'database': str(os.getenv('MYSQL_DB')),
      }
      
      def mysqlClient():
          print("connecting database ......")
          db = pymysql.connect(**config)
          try:
              cursor = db.cursor()
              cursor.execute("INSERT INTO username(user) VALUES('Mrs')")
              cursor.close()
              db.commit()
      
              cursor = db.cursor()
              cursor.execute("SELECT user FROM username")
              result = cursor.fetchall()
              cursor.close()
              if result != None:
                  print(result)
                  time.sleep(99999)
          except Exception as e:
              print('System Error: ', e)
          finally:
              db.close()
      
      
      if __name__ == '__main__':
          mysqlClient()
  6. Log on to the ApsaraDB RDS database and view the connection result.

    1. Log on to the ApsaraDB RDS console.

    2. In the left-side navigation pane, click Instances. In the top navigation bar, select the region in which the ApsaraDB RDS instance is deployed. Then, find the instance and click the instance ID.

    3. In the left-side navigation pane, click Databases.

    4. Find the ApsaraDB RDS database that you want to view. Click SQL Query.

    5. In the dialog box that appears, enter the username and password of the ApsaraDB RDS database and click Log In.

    6. Enter the SQL command to query the result.

      Run the SELECT * FROM 'username' command. You can see that a data entry is added to the user column of the username table.

      对接RDS

FAQ

The following part describes the common reasons why your ApsaraDB RDS database fails to connect to Elastic Container Instance:

  • Different network types

  • Different VPCs

  • Domain name resolution failures or errors

  • Different regions

  • Incorrect IP address whitelist settings

  • No IP address whitelist configured for a read-only instance

  • Invalid internal or public endpoint

  • Exhausted connection quota

  • Invalid username or password

  • Invalid host address

Select a solution based on the network type that you use to connect to the ApsaraDB RDS instance. For more information, see What do I do if I fail to connect an ApsaraDB for RDS instance?