To connect your containerized application to a database, such as an ApsaraDB RDS for MySQL instance, you must configure the whitelist of the ApsaraDB RDS instance and provide the database connection information when you create an ECI pod. This topic describes how to connect to ApsaraDB RDS when you create an ECI pod in an ACK Serverless cluster.
Background
ApsaraDB RDS is a stable, reliable, and scalable online database service from Alibaba Cloud. Built on the Alibaba Cloud distributed file system and high-performance solid-state drives (SSDs), ApsaraDB RDS supports multiple database engines, such as MySQL, SQL Server, and PostgreSQL. This topic uses an ApsaraDB RDS for MySQL instance as an example. You can select a database engine based on your business requirements. For more information, see Database engines.
Prerequisites
-
An ApsaraDB RDS for MySQL instance is created and a database account is configured for the instance. For more information, see Create an ApsaraDB RDS for MySQL instance and Create a database and an account.
-
An ACK Serverless cluster is created. For more information, see Create an ACK Serverless cluster.
NoteThis topic uses an ACK Serverless cluster as an example. If you use a different type of Kubernetes cluster, make sure that a virtual node is deployed in the cluster to connect to ECI.
-
The ApsaraDB RDS instance and the Kubernetes cluster can communicate with each other.
For optimal performance and security, deploy the ApsaraDB RDS instance and the Kubernetes cluster in the same Virtual Private Cloud (VPC). This enables internal network communication. If they are in different VPCs, you must configure access over the public network.
Configure the RDS whitelist and get the endpoint
Access RDS over the internal network
If your Kubernetes cluster and ApsaraDB RDS instance are in the same VPC, your application can access the instance over the internal network. Configure the ApsaraDB RDS whitelist and obtain the internal endpoint.
-
Configure the ApsaraDB RDS whitelist.
When you connect over the internal network, you can add an IP address or a security group to the whitelist:
-
IP address
Add the CIDR block of the VPC or vSwitch to the ApsaraDB RDS whitelist. This allows all ECI instances in the CIDR block to access the ApsaraDB RDS instance. For more information, see Configure an IP address whitelist.
-
Security group
Add the security group of your ECI instances to the ApsaraDB RDS whitelist. This allows all ECI instances in the security group to access the ApsaraDB RDS instance. For more information, see Configure a security group.
-
-
On the Database Connection page of the ApsaraDB RDS instance, find and record the internal endpoint.
Access RDS over the public network
If your Kubernetes cluster and ApsaraDB RDS instance are in different VPCs, your application must connect over the public network. Configure the ApsaraDB RDS whitelist and apply for a public endpoint.
-
Using a public endpoint can expose your instance to security risks. Use this option with caution.
-
For faster data transfer and higher security, we recommend migrating your application to an ECI instance in the same region and network as your ApsaraDB RDS instance, and then using the internal endpoint.
-
Configure the ApsaraDB RDS whitelist.
When you connect over the public network, you must configure an IP address whitelist. For more information, see Configure an IP address whitelist.
-
If your ECI instance uses a NAT gateway to access the public network, add the Elastic IP address (EIP) of the NAT gateway to the IP address whitelist.
-
If your ECI instance uses an EIP to access the public network, add the EIP of the ECI instance to the IP address whitelist.
-
-
Apply for and record the public endpoint of the database. For more information, see Apply for or release a public endpoint.
Configure an application to connect to RDS
This procedure shows how to connect an ACK Serverless cluster to an ApsaraDB RDS instance over an internal network.
-
Log on to the ACK console.
-
On the Cluster page, find your target cluster and click its name to open the cluster details page.
-
Create a ConfigMap to store the ApsaraDB RDS connection information.
NoteA ConfigMap decouples environment configuration from the container image. This simplifies application configuration updates.
-
In the left-side navigation pane, choose Configuration > ConfigMaps.
-
Click Create.
-
Enter the ConfigMap details and click OK.
Set the name to
rds-configand add the following key-value pairs:Parameter
Example
Description
host
rm-2zem97a62s9******.mysql.rds.aliyuncs.com
The database endpoint. Available on the Database Connection page of your ApsaraDB RDS instance.
port
3306
The database port. Available on the Database Connection page of your ApsaraDB RDS instance.
database
test-db
The database name. Available on the Databases page of your ApsaraDB RDS instance.
-
-
Create a Secret to store the database username and password.
NoteUsing a Secret is a best practice for securely managing sensitive information, such as database credentials, for your application.
-
In the left-side navigation pane, choose Configuration > Secrets.
-
Click Create.
-
Enter the Secret details and click OK.
Set the name to
rds-secretand add the following key-value pairs:Parameter
Example
Description
username
test
The database username. Available on the Accounts page of your ApsaraDB RDS instance.
password
pwd******
The database password. If you forget the password, reset it on the Accounts page of your ApsaraDB RDS instance.
-
-
Create an ECI pod to test the connection.
-
In the left-side navigation pane, choose Workloads > Pods.
-
Click Create from YAML.
-
Enter the YAML configuration and click Create.
ApsaraDB RDS is fully compatible with native database services. You can use any standard database client to connect to your ApsaraDB RDS instance. The following YAML file is an example:
NoteTo use this example, you must first create a table named
usernamewith a column nameduserin your ApsaraDB RDS instance.The following YAML configuration uses environment variables to provide the database connection details: endpoint, port, name, username, and password. The container image includes a Python script that connects to the database and inserts 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 # A container image that contains a Python script to connect to the database. 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: NeverThe image in the preceding example contains a Python script (
mysqlclient.py) that inserts a row into theusercolumn of theusernametable. The script is as follows: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 to the 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()
-
-
Log on to the database and verify the result.
-
Log on to the ApsaraDB RDS console.
-
In the left-side navigation pane, click Instances. In the top navigation bar, select the region where your instance is located, and then click the instance ID.
-
In the left-side navigation pane, click Databases.
-
Find the target database and click SQL Query in the Actions column.
-
In the dialog box that appears, enter the database username and password, and then click Log In.
-
Run an SQL command to check the result.
Run the
SELECT * FROM `username`command. The output shows a new row in the user column of the username table.
-
FAQ
Common reasons for database connection failures include:
-
Different network types
-
Different VPCs
-
Domain name resolution failure or error
-
Different regions
-
Incorrect IP address whitelist configuration
-
Whitelist not configured for a read-only instance
-
Incorrect use of internal or public endpoints
-
Connection limit reached
-
Incorrect username or password
-
Unable to resolve the endpoint
Troubleshoot the issue based on your network environment (internal network or public network). For more information, see Troubleshoot ApsaraDB RDS connection failures.