

# 在 Amazon ECS 任务定义中指定容器重启策略
<a name="container-restart-policy-example"></a>

要在任务定义中为容器指定重启策略，请在容器定义中指定 `restartPolicy` 对象。有关 `restartPolicy` 对象的更多信息，请参阅[重启策略](task_definition_parameters.md#container_definition_restart_policy)。

下面的任务定义使用 Fargate 上的 Linux 容器来设置 Web 服务器。该容器定义包括 `restartPolicy` 对象，并将 `enabled` 设置为 true 以为该容器启用重启策略。容器必须运行 180 秒后才能重启，并且如果容器以退出代码 `0` 退出，则表示成功，也不会重启容器。

```
{
  "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"
        }
      ],
      "restartPolicy": {
        "enabled": true,
        "ignoredExitCodes": [0],
        "restartAttemptPeriod": 180
      }
    }
  ],
  "cpu": "256",
  "executionRoleArn": "arn:aws:iam::012345678910:role/ecsTaskExecutionRole",
  "family": "fargate-task-definition",
  "memory": "512",
  "networkMode": "awsvpc",
  "runtimePlatform": {
    "operatingSystemFamily": "LINUX"
  },
  "requiresCompatibilities": ["FARGATE"]
}
```

将任务定义注册到容器定义中的 `restartPolicy` 对象后，您可以使用该任务定义运行任务或创建服务。有关更多信息，请参阅[将应用程序作为 Amazon ECS 任务运行](standalone-task-create.md)和[创建 Amazon ECS 滚动更新部署](create-service-console-v2.md)。