Amazon ECS 태스크 정의 예제

Amazon ECS 태스크 정의 예제

예제와 스니펫을 복사해 자체 태스크 정의를 만들기 시작할 수 있어요. 예제를 복사한 다음 콘솔에서 Configure via JSON 옵션을 사용할 때 붙여 넣을 수 있어요. 계정 ID를 사용하는 것처럼 예제를 사용자 정의해야 해요. 태스크 정의 JSON에 스니펫을 포함할 수 있어요. 자세한 내용은 Creating an Amazon ECS task definition using the console과 Amazon ECS task definition parameters for Fargate를 참고하세요. 더 많은 태스크 정의 예제는 GitHub의 AWS Sample Task Definitions를 참고하세요.

출처: 문서

본문

토픽

  • 웹 서버 (Webserver)
  • splunk 로그 드라이버
  • fluentd 로그 드라이버
  • gelf 로그 드라이버
  • 외부 인스턴스의 워크로드
  • Amazon ECR 이미지 및 태스크 정의 IAM 역할
  • 명령이 있는 엔트리포인트 (Entrypoint with command)
  • 컨테이너 의존성 (Container dependency)
  • 태스크 정의의 볼륨 (Volumes in task definitions)
  • Windows 샘플 태스크 정의

웹 서버 (Webserver)

다음은 Fargate에서 Linux 컨테이너를 사용해 웹 서버를 설정하는 태스크 정의 예제예요.

{
   "containerDefinitions": [ 
      { 
         "command": [
            "/bin/sh -c \"echo '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p> </div></body></html>' >  /usr/local/apache2/htdocs/index.html && httpd-foreground\""
         ],
         "entryPoint": [
            "sh",
            "-c"
         ],
         "essential": true,
         "image": "public.ecr.aws/docker/library/httpd:2.4",
         "logConfiguration": { 
            "logDriver": "awslogs",
            "options": { 
               "awslogs-group" : "/ecs/fargate-task-definition",
               "awslogs-region": "us-east-1",
               "awslogs-stream-prefix": "ecs"
            }
         },
         "name": "sample-fargate-app",
         "portMappings": [ 
            { 
               "containerPort": 80,
               "hostPort": 80,
               "protocol": "tcp"
            }
         ]
      }
   ],
   "cpu": "256",
   "executionRoleArn": "arn:aws:iam::012345678910:role/ecsTaskExecutionRole",
   "family": "fargate-task-definition",
   "memory": "512",
   "networkMode": "awsvpc",
   "runtimePlatform": {
        "operatingSystemFamily": "LINUX"
    },
   "requiresCompatibilities": [ 
       "FARGATE" 
    ]
}

다음은 Fargate에서 Windows 컨테이너를 사용해 웹 서버를 설정하는 태스크 정의 예제예요.

{
    "containerDefinitions": [
        {
            "command": ["New-Item -Path C:\\inetpub\\wwwroot\\index.html -Type file -Value '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p>'; C:\\ServiceMonitor.exe w3svc"],
            "entryPoint": [
                "powershell",
                "-Command"
            ],
            "essential": true,
            "cpu": 2048,
            "memory": 4096,
            "image": "mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019",
            "name": "sample_windows_app",
            "portMappings": [
                {
                    "hostPort": 80,
                    "containerPort": 80,
                    "protocol": "tcp"
                }
            ]
        }
    ],
    "memory": "4096",
    "cpu": "2048",
    "networkMode": "awsvpc",
    "family": "windows-simple-iis-2019-core",
    "executionRoleArn": "arn:aws:iam::012345678910:role/ecsTaskExecutionRole",
    "runtimePlatform": {"operatingSystemFamily": "WINDOWS_SERVER_2019_CORE"},
    "requiresCompatibilities": ["FARGATE"]
}

splunk 로그 드라이버

다음 스니펫은 로그를 원격 서비스로 보내는 태스크 정의에서 splunk 로그 드라이버를 사용하는 방법을 보여 줘요. Splunk 토큰 파라미터는 민감한 데이터로 취급될 수 있으므로 시크릿 옵션으로 지정돼요. 자세한 내용은 Pass sensitive data to an Amazon ECS container을 참고하세요.

"containerDefinitions": [{
		"logConfiguration": {
			"logDriver": "splunk",
			"options": {
				"splunk-url": "https://cloud.splunk.com:8080",
				"tag": "tag_name",
			},
			"secretOptions": [{
				"name": "splunk-token",
				"valueFrom": "arn:aws:secretsmanager:region:aws_account_id:secret:splunk-token-KnrBkD"
}],

fluentd 로그 드라이버

다음 스니펫은 로그를 원격 서비스로 보내는 태스크 정의에서 fluentd 로그 드라이버를 사용하는 방법을 보여 줘요. fluentd-address 값은 민감한 데이터로 취급될 수 있으므로 시크릿 옵션으로 지정돼요. 자세한 내용은 Pass sensitive data to an Amazon ECS container을 참고하세요.

"containerDefinitions": [{
	"logConfiguration": {
		"logDriver": "fluentd",
		"options": {
			"tag": "fluentd demo"
		},
		"secretOptions": [{
			"name": "fluentd-address",
			"valueFrom": "arn:aws:secretsmanager:region:aws_account_id:secret:fluentd-address-KnrBkD"
		}]
	},
	"entryPoint": [],
	"portMappings": [{
             "hostPort": 80,
             "protocol": "tcp",
             "containerPort": 80
             },
             {
		"hostPort": 24224,
		"protocol": "tcp",
		"containerPort": 24224
	}]
}],

gelf 로그 드라이버

다음 스니펫은 Gelf 로그를 입력으로 받는 Logstash를 실행하는 원격 호스트로 로그를 보내는 태스크 정의에서 gelf 로그 드라이버를 사용하는 방법을 보여 줘요. 자세한 내용은 logConfiguration을 참고하세요.

"containerDefinitions": [{
	"logConfiguration": {
		"logDriver": "gelf",
		"options": {
			"gelf-address": "udp://logstash-service-address:5000",
			"tag": "gelf task demo"
		}
	},
	"entryPoint": [],
	"portMappings": [{
			"hostPort": 5000,
			"protocol": "udp",
			"containerPort": 5000
		},
		{
			"hostPort": 5000,
			"protocol": "tcp",
			"containerPort": 5000
		}
	]
}],

외부 인스턴스의 워크로드 (Workloads on external instances)

Amazon ECS 태스크 정의를 등록할 때 requiresCompatibilities 파라미터를 사용하고 EXTERNAL을 지정하세요. 이는 태스크 정의가 외부 인스턴스에서 Amazon ECS 워크로드를 실행할 때 호환되는지 검증해요. 콘솔을 사용해 태스크 정의를 등록한다면 JSON 편집기를 사용해야 해요. 자세한 내용은 Creating an Amazon ECS task definition using the console을 참고하세요. 중요: 태스크에 태스크 실행 IAM 역할이 필요하다면 태스크 정의에 지정되어 있는지 확인하세요. 워크로드를 배포할 때는 서비스를 만들거나 standalone 태스크를 실행할 때 EXTERNAL 실행 유형을 사용하세요.

Linux

{
	"requiresCompatibilities": [
		"EXTERNAL"
	],
	"containerDefinitions": [{
		"name": "nginx",
		"image": "public.ecr.aws/nginx/nginx:latest",
		"memory": 256,
		"cpu": 256,
		"essential": true,
		"portMappings": [{
			"containerPort": 80,
			"hostPort": 8080,
			"protocol": "tcp"
		}]
	}],
	"networkMode": "bridge",
	"family": "nginx"
}

Windows

{
	"requiresCompatibilities": [
		"EXTERNAL"
	],
	"containerDefinitions": [{
		"name": "windows-container",
		"image": "mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019",
		"memory": 256,
		"cpu": 512,
		"essential": true,
		"portMappings": [{
			"containerPort": 80,
			"hostPort": 8080,
			"protocol": "tcp"
		}]
	}],
	"networkMode": "bridge",
	"family": "windows-container"
}

Amazon ECR 이미지 및 태스크 정의 IAM 역할

다음 스니펫은 123456789012.dkr.ecr.us-west-2.amazonaws.com 레지스트리에서 v1 태그가 있는 aws-nodejs-sample이라는 Amazon ECR 이미지를 사용해요. 이 태스크의 컨테이너는 arn:aws:iam::123456789012:role/AmazonECSTaskS3BucketRole 역할에서 IAM 권한을 상속해요. 자세한 내용은 Amazon ECS task IAM role을 참고하세요.

{
    "containerDefinitions": [
        {
            "name": "sample-app",
            "image": "123456789012.dkr.ecr.us-west-2.amazonaws.com/aws-nodejs-sample:v1",
            "memory": 200,
            "cpu": 10,
            "essential": true
        }
    ],
    "family": "example_task_3",
    "taskRoleArn": "arn:aws:iam::123456789012:role/AmazonECSTaskS3BucketRole"
}

명령이 있는 엔트리포인트 (Entrypoint with command)

다음 스니펫은 엔트리 포인트와 명령 인수를 사용하는 Docker 컨테이너의 구문을 보여 줘요. 이 컨테이너는 example.com을 네 번 ping 한 다음 종료돼요.

{
    "containerDefinitions": [
        {
            "memory": 32,
            "essential": true,
            "entryPoint": ["ping"],
            "name": "alpine_ping",
            "readonlyRootFilesystem": true,
            "image": "alpine:3.4",
            "command": [
                "-c",
                "4",
                "example.com"
            ],
            "cpu": 16
        }
    ],
    "family": "example_task_2"
}

컨테이너 의존성 (Container dependency)

이 스니펫은 컨테이너 의존성이 지정된 여러 컨테이너가 있는 태스크 정의의 구문을 보여 줘요. 다음 태스크 정의에서 envoy 컨테이너는 필수 컨테이너 상태 검사 파라미터로 결정되는 정상 상태에 도달해야 app 컨테이너가 시작돼요. 자세한 내용은 Container dependency를 참고하세요.

{
  "family": "appmesh-gateway",
  "runtimePlatform": {
        "operatingSystemFamily": "LINUX"
  },
  "proxyConfiguration":{
      "type": "APPMESH",
      "containerName": "envoy",
      "properties": [
          {
              "name": "IgnoredUID",
              "value": "1337"
          },
          {
              "name": "ProxyIngressPort",
              "value": "15000"
          },
          {
              "name": "ProxyEgressPort",
              "value": "15001"
          },
          {
              "name": "AppPorts",
              "value": "9080"
          },
          {
              "name": "EgressIgnoredIPs",
              "value": "169.254.170.2,169.254.169.254"
          }
      ]
  },
  "containerDefinitions": [
    {
      "name": "app",
      "image": "application_image",
      "portMappings": [
        {
          "containerPort": 9080,
          "hostPort": 9080,
          "protocol": "tcp"
        }
      ],
      "essential": true,
      "dependsOn": [
        {
          "containerName": "envoy",
          "condition": "HEALTHY"
        }
      ]
    },
    {
      "name": "envoy",
      "image": "840364872350.dkr.ecr.region-code.amazonaws.com/aws-appmesh-envoy:v1.15.1.0-prod",
      "essential": true,
      "environment": [
        {
          "name": "APPMESH_VIRTUAL_NODE_NAME",
          "value": "mesh/meshName/virtualNode/virtualNodeName"
        },
        {
          "name": "ENVOY_LOG_LEVEL",
          "value": "info"
        }
      ],
      "healthCheck": {
        "command": [
          "CMD-SHELL",
          "echo hello"
        ],
        "interval": 5,
        "timeout": 2,
        "retries": 3
      }    
    }
  ],
  "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
  "networkMode": "awsvpc"
}

태스크 정의의 볼륨 (Volumes in task definitions)

태스크에서 볼륨을 지정하는 방법을 이해하려면 다음을 사용하세요.

  • Amazon EBS 볼륨을 구성하는 방법은 Specify Amazon EBS volume configuration at Amazon ECS deployment를 참고하세요.
  • Amazon EFS 볼륨을 구성하는 방법은 Configuring Amazon EFS file systems for Amazon ECS using the console을 참고하세요.
  • FSx for Windows File Server 볼륨을 구성하는 방법은 Learn how to configure FSx for Windows File Server file systems for Amazon ECS를 참고하세요.
  • Docker 볼륨을 구성하는 방법은 Docker volume examples for Amazon ECS를 참고하세요.
  • 바인드 마운트를 구성하는 방법은 Bind mount examples for Amazon ECS를 참고하세요.

Windows 샘플 태스크 정의

다음은 Amazon ECS에서 Windows 컨테이너를 시작하는 데 도움이 되는 샘플 태스크 정의예요.

Windows용 Amazon ECS 콘솔 샘플 애플리케이션 예제 – 다음 태스크 정의는 Amazon ECS의 첫 실행 마법사에서 생성되는 Amazon ECS 콘솔 샘플 애플리케이션이며, microsoft/iis Windows 컨테이너 이미지를 사용하도록 포팅된 것이에요.

{
  "family": "windows-simple-iis",
  "containerDefinitions": [
    {
      "name": "windows_sample_app",
      "image": "mcr.microsoft.com/windows/servercore/iis",
      "cpu": 1024,
      "entryPoint":["powershell", "-Command"],
      "command":["New-Item -Path C:\\inetpub\\wwwroot\\index.html -Type file -Value '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p>'; C:\\ServiceMonitor.exe w3svc"],
      "portMappings": [
        {
          "protocol": "tcp",
          "containerPort": 80
        }
      ],
      "memory": 1024,
      "essential": true
    }
  ],
  "networkMode": "awsvpc",
  "memory": "1024",
  "cpu": "1024"
}