Search code examples
amazon-web-servicesdockeramazon-ecsamazon-ecr

Easily run a single Dockerfile on AWS


Let’s say I’ve a simple standalone Dockerfile with its entrypoint.sh. The container is already built and stored on AWS ECR.

Locally, I run it like this:

docker run —rm my_container my_parameters

I don’t need load balancing, neither keep the container alive after execution, just to be executable on demand (through AWS API).

What is the simplest way to do this on AWS?


Solution

  • Here is the top 3 layer to run simplest container on AWS.

    1. Create Cluster
    2. Create Task definition
    3. Create Service

    But in the above sequence, your command docker run —rm my_container my_parameters fall at layer 3. As layer 1 need be created only once throughout the life cycle and layer 2 needs to be updated if any changes required like port updating or any ENV in Task definition but again this is not frequent in some cases.

    So better to manage the layer3 using API or AWS CLI. As you mentioned on demand so you can run also using schedule based container that will run and stop on the specific time.

    The bash script will create task definition (template), start service (run container) and stop service in another (stop container).

    #!/bin/bash
    AWS_PROFILE="test"
    COMMAND="${1}"
    ECS_CLUSTER="test"
    if [ "${COMMAND}" == "setup_task" ]; then
    aws ecs register-task-definition --cli-input-json file://taskdefinition.json --profile $AWS_PROFILE
    elif [ "${COMMAND}" == "run_container" ]; then
    aws ecs create-service  --cluster $ECS_CLUSTER  --service-name ecs-simple-service    --task-definition nginx    --desired-count 1 --profile $AWS_PROFILE
    elif [ "${COMMAND}" == "stop_container" ];then
    aws ecs delete-service --cluster $ECS_CLUSTER --service ecs-simple-service --force --profile $AWS_PROFILE
    else
    >&2 echo "Wrong Argument passed! Valid option is setup_task, run_container and stop_container"
    fi
    

    taskdefinition

    taskdefinition.json

    
    {
      "containerDefinitions": [
      {
        "cpu": 0,
        "logConfiguration": {
          "logDriver": "awslogs",
          "options": {
            "awslogs-group": "/ecs/stage-background-worker",
            "awslogs-region": "us-west-2",
            "awslogs-stream-prefix": "ecs"
      }
    },
        "environment": [
          {
            "name": "NODE_ENV",
            "value": "staging"
          }
        ],
    
    
        "memoryReservation": 400,
        "image": "youarn.dkr.ecr.us-west-2.amazonaws.com:latest",
        "dockerLabels": {
          "Name": "test"
        },
        "privileged": true,
        "name": "test"
      }
    ],
    
    "family": "test"
    }
    
    

    This based on AWS-CLI, you can explore the same for any programming language here.