我想從 AWS Fargate 上的 Amazon Elastic Container Service (Amazon ECS) 任務連接到資料庫。
先決條件:
**注意:**以下範例使用 MySQL 作為引擎類型。如需引擎類型的詳細資訊,請參閱開始使用 Amazon RDS。
請完成下列步驟:
import pymysqlimport os Database_endpoint = os.environ['ENDPOINT'] Username = os.environ['USER'] Password = os.environ['PASS'] 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))
FROM pythonRUN pip install pymysql cryptography COPY rds.py / CMD [ "python", "/rds.py" ]
{ "executionRoleArn": "arn:aws:iam::account_ID:role/ecsTaskExecutionRole", "containerDefinitions": [ { "name": "sample-app", "image": "YOUR-ECR-Repository-URL", "essential": true } ], "requiresCompatibilities": [ "FARGATE" ], "networkMode": "awsvpc", "cpu": "256", "memory": "512", "family": "sample-app" }
rds.py 指令碼會停止任務並傳回下列訊息:
「任務中的必要容器已退出。」
您會在 CloudWatch 主控台中看到以下訊息:
「成功連線至 [Your Endpoint]」