

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon ECS 任務定義範例
<a name="example_task_definitions"></a>

您可以從複製範例與程式碼片段開始，著手建立自己的任務定義。

您可以複製範例，然後在使用主控台中的**透過 JSON 設定**選項時貼上。確保自定範例，例如使用您的帳戶 ID。您可以在任務定義 JSON 中包含這些程式碼片段。如需詳細資訊，請參閱[使用主控台建立 Amazon ECS 任務定義](create-task-definition.md)及[Fargate 的 Amazon ECS 任務定義參數](task_definition_parameters.md)。

如需更多任務定義範例，請參閱 GitHub 上的 [AWS 範例任務定義](https://github.com/aws-samples/aws-containers-task-definitions)。

**Topics**
+ [

## Web 伺服器
](#example_task_definition-webserver)
+ [

## `splunk` 日誌驅動程式
](#example_task_definition-splunk)
+ [

## `fluentd` 日誌驅動程式
](#example_task_definition-fluentd)
+ [

## `gelf` 日誌驅動程式
](#example_task_definition-gelf)
+ [

## 外部執行個體上的工作負載
](#ecs-anywhere-runtask)
+ [

## Amazon ECR 映像與任務定義 IAM 角色
](#example_task_definition-iam)
+ [

## 進入點與命令
](#example_task_definition-ping)
+ [

## 容器相依性
](#example_task_definition-containerdependency)
+ [

## 任務定義中的磁碟區
](#volume_sample_task_defs)
+ [

## Windows 任務定義範例
](#windows_sample_task_defs)

## Web 伺服器
<a name="example_task_definition-webserver"></a>

以下是使用 Fargate 上 Linux 容器並設定 Web 伺服器的任務定義範例：

```
{
   "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 容器並設定 Web 伺服器的任務定義範例：

```
{
    "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` 日誌驅動程式
<a name="example_task_definition-splunk"></a>

以下程式碼片段示範如何在任務定義中使用 `splunk` 日誌驅動程式將日誌傳送到遠端服務。Splunk 字符參數被指定為秘密選項，因為它可以視為敏感資料。如需詳細資訊，請參閱[將敏感資料傳遞至 Amazon ECS 容器](specifying-sensitive-data.md)。

```
"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` 日誌驅動程式
<a name="example_task_definition-fluentd"></a>

以下程式碼片段示範如何在任務定義中使用 `fluentd` 日誌驅動程式將日誌傳送到遠端服務。`fluentd-address` 值被指定為秘密選項，因為它可以視為敏感資料。如需詳細資訊，請參閱[將敏感資料傳遞至 Amazon ECS 容器](specifying-sensitive-data.md)。

```
"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` 日誌驅動程式
<a name="example_task_definition-gelf"></a>

以下程式碼片段示範如何在任務定義中使用 `gelf` 日誌驅動程式，將日誌傳送到執行 Logstash (以 Gelf 日誌做為輸入) 的遠端主機。如需詳細資訊，請參閱[logConfiguration](task_definition_parameters.md#ContainerDefinition-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
		}
	]
}],
```

## 外部執行個體上的工作負載
<a name="ecs-anywhere-runtask"></a>

註冊 Amazon ECS 任務定義時，請使用 `requiresCompatibilities` 參數並指定 `EXTERNAL`，這可驗證任務定義是相容的，可在外部執行個體上執行 Amazon ECS 工作負載時使用。如果您使用主控台註冊任務定義，則必須使用 JSON 編輯器。如需詳細資訊，請參閱[使用主控台建立 Amazon ECS 任務定義](create-task-definition.md)。

**重要**  
如果您的任務需要任務執行 IAM 角色，請確定在任務定義中指定它。

當您部署工作負載時，請在建立服務或執行獨立任務時使用 `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 角色
<a name="example_task_definition-iam"></a>

以下程式碼片段使用稱為 `aws-nodejs-sample` 的 Amazon ECR 映像，具有來自 `123456789012.dkr.ecr.us-west-2.amazonaws.com` 登錄檔的 `v1` 標籤。此任務中的容器會繼承 `arn:aws:iam::123456789012:role/AmazonECSTaskS3BucketRole` 角色的 IAM 許可。如需詳細資訊，請參閱[Amazon ECS 任務 IAM 角色](task-iam-roles.md)。

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

## 進入點與命令
<a name="example_task_definition-ping"></a>

以下程式碼片段會示範使用進入點和命令引數的 Docker 容器語法。此容器 ping `example.com` 四次，然後結束。

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

## 容器相依性
<a name="example_task_definition-containerdependency"></a>

此程式碼片段示範任務定義的語法，其中有多個容器且指定容器相依性。在以下任務定義中，`envoy` 容器必須達到運作良好狀態 (由必要的容器運作狀態檢查參數來判斷)，`app` 容器才會啟動。如需詳細資訊，請參閱[容器相依性](task_definition_parameters.md#container_definition_dependson)。

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

## 任務定義中的磁碟區
<a name="volume_sample_task_defs"></a>

請參閱下列主題，了解如何在任務中指定磁碟區。
+ 如需有關如何設定 Amazon EBS 磁碟區的資訊，請參閱[在部署 Amazon ECS 時指定 Amazon EBS 磁碟區組態](configure-ebs-volume.md)。
+ 如需有關如何設定 Amazon EFS 磁碟區的資訊，請參閱[使用主控台為 Amazon ECS 設定 Amazon EFS 檔案系統](tutorial-efs-volumes.md)。
+ 如需有關如何設定 FSx for Windows File Server 磁碟區的資訊，請參閱[了解如何為 Amazon ECS 設定 FSx for Windows File Server 檔案系統](tutorial-wfsx-volumes.md)。
+ 如需有關如何設定 Docker 磁碟區的資訊，請參閱 [Amazon ECS 的 Docker 磁碟區範例](docker-volume-examples.md)。
+ 如需有關如何設定綁定掛載的資訊，請參閱[Amazon ECS 的綁定掛載範例](bind-mount-examples.md)。

## Windows 任務定義範例
<a name="windows_sample_task_defs"></a>

以下任務定義範例可協助您在 Amazon ECS 上開始使用 Windows 容器。

**Example 適用於 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"
}
```