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

3 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 example uses MySQL as the engine type. For more information on 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 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))
    Note: Replace ENDPOINT, USER, and PASS with your database values.
  2. To assemble an image, create a Dockerfile that includes the required commands. For example:
    FROM pythonRUN pip install pymysql cryptography
    COPY rds.py /
    CMD [ "python", "/rds.py" ]
    Important: Put your rds.py script and Dockerfile in the same folder.
  3. Create an Amazon ECR repository, and then push the Docker image to that repository.
  4. Create a task definition, and then add the Docker image as the container image. For example:
    {
      "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"
    }
    Note: In your task definition, set the values for the ENDPOINT, USER, and PASS environment variables. 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 pass secrets or sensitive information securely 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 copied.
  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.

The rds.py script stops the task and returns the following message:

"Essential container in task exited."

Confirm that your task is connected 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, in the Containers section, expand the section.
  7. Choose View logs in CloudWatch.

You see the following message in the CloudWatch console:

"Connection successful to [Your Endpoint]"

AWS OFFICIAL
AWS OFFICIALUpdated 4 months ago
2 Comments

Hi! How would this change if the database is a MS SQL server located in a EC2 instance in a VPC? Thank you

jbelis
replied a month ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

profile pictureAWS
MODERATOR
replied a month ago