Skip to content

How do I connect to a database from an Amazon ECS task on Fargate?

4 minute read
0

I want to connect to a database from an Amazon Elastic Container Service (Amazon ECS) task on AWS Fargate.

Resolution 

Prerequisites:

Note: The following resolution uses a MySQL database engine. For more information on how to connect to databases that use other engine types, see Getting started with Amazon RDS.

Connect your task to your database

Complete the following steps:

  1. Create a Python script that connects to your MySQL database. The following example rds.py script sends the results of the connection to the database to 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))

    Note: Replace example_endpoint with your database end point. Replace example_username with your username. Replace example_password with your password.

  2. To assemble an image, create a Dockerfile that includes the required commands. The following example file includes the necessary commands:

    FROM python
    RUN pip install pymysql cryptography
    COPY rds.py /
    CMD [ "python", "/rds.py" ]
  3. Create an Amazon Elastic Container Registry (Amazon ECR) repository, and then push your Docker image to that repository.

  4. Create a task definition, and then add your Docker image as the container image:

    {  "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"
    }

    Note: Replace example_account_ID with your AWS account ID. Replace example_app with the name of your application. Replace example_repository_URL with the URL of your Amazon ECR repository. It's a best practice to set the values for the ENDPOINT, USER, and PASS environment variables in your task definition. You can directly pass these values as environment variables or retrieve the values from secrets in AWS Secrets Manager. For more information, see How can I securely pass secrets or sensitive information to containers in an Amazon ECS task?

  5. Open the Amazon ECS console.

  6. In the navigation pane, choose Task Definitions.

  7. Select your task definition, choose Actions, and then choose Run Task.

  8. For Launch type, choose FARGATE.

  9. For Cluster, choose the cluster for your task definition.

  10. For Number of tasks, enter the number of tasks that you want to run.

  11. In the VPC and security groups section, for Cluster VPC, choose your Amazon Virtual Private Cloud (Amazon VPC).

  12. For Subnets, choose your subnets.

  13. For Security groups, select at least one security group.

  14. Choose Run Task.

When your task is connects to your database, the rds.py script stops the task and displays the following message:

"Essential container in task exited."

Confirm that you connected your task to your database

Complete the following steps:

  1. Open the Amazon ECS console.
  2. In the navigation pane, choose Clusters, and then choose your cluster.
  3. Choose the Tasks tab.
  4. For Desired task status, to see a list of stopped tasks, choose Stopped.
  5. Choose your stopped task.
  6. On the Details tab of your stopped task, expand the Containers section.
  7. Choose View logs in CloudWatch.

If you successfully connected your task to your database, then the following message displays in the CloudWatch console:

"Connection successful to [your endpoint]"

AWS OFFICIALUpdated 2 months ago