我想要從 AWS Fargate 上的 Amazon Elastic Container Service (Amazon ECS) 任務連線到資料庫。
解決方法
先決條件:
**注意:**以下解決方法使用 MySQL 資料庫引擎。如需連線至使用其他引擎類型資料庫的詳細資訊,請參閱 Amazon RDS 入門。
將您的任務連線至資料庫
請完成以下步驟:
-
建立連線至 MySQL 資料庫的 Python 指令碼。以下範例 rds.py 指令碼會將資料庫連線結果傳送至 Amazon CloudWatch:
import pymysql
import os
DATABASE_ENDPOINT = os.environ['example_endpoint']
USERNAME = os.environ['example_username']
PASSWORD = os.environ['example_password']
try:
print("Connecting to " + DATABASE_ENDPOINT)
db = pymysql.connect(host=DATABASE_ENDPOINT, user=USERNAME, password=PASSWORD)
print("Connection successful to " + DATABASE_ENDPOINT)
db.close()
except Exception as e:
print("Connection unsuccessful due to " + str(e))
**注意:**將 example_endpoint 替換為您的資料庫端點。將 example_username 替換為您的使用者名稱。將 example_password 替換為您的密碼。
-
若要組建映像檔,請建立包含所需命令的 Dockerfile。以下範例檔案包含必要命令:
FROM python
RUN pip install pymysql cryptography
COPY rds.py /
CMD [ "python", "/rds.py" ]
-
建立 Amazon Elastic Container Registry (Amazon ECR) 儲存庫,然後將您的 Docker 映像檔推送至該儲存庫。
-
建立任務定義,然後將您的 Docker 映像檔新增為容器映像檔:
{ "executionRoleArn": "arn:aws:iam::example_account_ID:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "example_app",
"image": "example_repository_URL",
"essential": true
}
],
"requiresCompatibilities": [
"FARGATE"
],
"networkMode": "awsvpc",
"cpu": "256",
"memory": "512",
"family": "example_app"
}
**注意:**將 example_account_ID 替換為您的 AWS 帳戶 ID。將 example_app 替換為您的應用程式名稱。將 example_repository_URL 替換為 Amazon ECR 儲存庫的網址。最佳實務是在任務定義中設定 ENDPOINT、USER 和 PASS 環境變數的值。您可以直接將這些值以環境變數傳遞,或從 AWS Secrets Manager 的祕密擷取這些值。如需更多資訊,請參閱如何將祕密或敏感資訊安全地傳遞至 Amazon ECS 任務中的容器?
-
開啟 Amazon ECS console (Amazon ECS 主控台)。
-
在導覽窗格中,選擇 Task Definitions (任務定義)。
-
選取您的任務定義,選擇 Actions (動作),然後選擇 Run Task (執行任務)。
-
在 Launch type (啟動類型),選擇 FARGATE。
-
在 Cluster (叢集),選擇您任務定義的叢集。
-
在 Number of tasks (任務數量),輸入您要執行的任務數量。
-
在 VPC and security groups (VPC 和安全群組) 區段中,於 Cluster VPC (叢集 VPC),選擇您的 Amazon Virtual Private Cloud (Amazon VPC)。
-
在 Subnets (子網路),選擇您的子網路。
-
在 Security groups (安全群組),選取至少一個安全群組。
-
選擇 Run Task (執行任務)。
當您的任務連線至資料庫時,rds.py 指令碼會停止任務並顯示以下訊息:
「Essential container in task exited.」
確認您已將任務連線至資料庫
請完成以下步驟:
- 開啟 Amazon ECS 主控台。
- 在導覽窗格中,選擇 Clusters (叢集),然後選擇您的叢集。
- 選擇 Tasks (任務) 索引標籤。
- 在 Desired task status (所需任務狀態),若要查看已停止任務的清單,請選擇 Stopped (已停止)。
- 選擇您的已停止的任務。
- 在已停止任務的 Details (詳細資訊) 索引標籤上,展開 Containers (容器) 區段。
- 選擇 View logs in CloudWatch (在 CloudWatch 中檢視日誌)。
如果您已成功將任務連線至資料庫,則 CloudWatch 主控台會顯示以下訊息:
「Connection successful to [your endpoint]」