October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk9 min

Deploy a Secure Containerized App on Amazon ECS Fargate Using ECR and Secrets Manager

Deploy a container on ECS Fargate from ECR, inject Secrets Manager values, separate the execution and task roles, and set private networking correctly.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To run a container on AWS Fargate with its image pulled from Amazon ECR and its sensitive settings supplied by AWS Secrets Manager, you need four pieces working together: a versioned image in a private ECR repository, a secret that is readable by one execution role only, a task definition that names both roles and references the secret, and a service whose network path lets the task reach ECR and Secrets Manager without exposing it to the internet. This walkthrough follows the sequence in AWS’s own Fargate and secrets tutorials and adds the security decisions those tutorials leave to the reader.

AWS console labels, CLI behavior, and platform-version details change over time. The AWS pages linked below are the reference point for the steps as of October 2026. Check them before you apply the version-specific details to production.

As an Amazon Associate I earn from qualifying purchases.

What you need before you start

  • An AWS account with permission to create ECR repositories, Secrets Manager secrets, ECS clusters, services and task definitions, and IAM roles.
  • AWS CLI version 2 configured for one region. Every resource in this walkthrough must be in that same region.
  • Docker on the machine that builds the image.
  • A VPC with at least two private subnets in different Availability Zones, plus a security group for the service and, if you expose the app, an Application Load Balancer.

Two roles, two jobs

Most misconfigurations in this setup come from mixing up the two IAM roles a Fargate task can use. The task execution role is used by the ECS and Fargate agent, acting on the task’s behalf. The task role is used by your application code when it calls AWS APIs. They are separate roles and should stay separate. The Amazon ECS IAM best practices guidance recommends separate roles and narrowing permissions to the resources actually needed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Role Who uses it What it needs for this deployment What it should not contain
Task execution role The ECS/Fargate agent Pull the private image from ECR, write container logs when the awslogs driver is used, and retrieve the specific secret referenced in the task definition Application data permissions, such as broad S3 or DynamoDB access
Task role Your application code, through the AWS SDK Only the AWS API calls the app makes at runtime, for example reading one S3 prefix Anything the app does not call. If the app makes no AWS API calls, omit this role entirely

For the execution role, attach the AWS managed policy AmazonECSTaskExecutionRolePolicy, which covers the ECR pull and CloudWatch Logs actions, and add a separate inline policy that grants secretsmanager:GetSecretValue on the one secret ARN. Do not grant secretsmanager:* or a wildcard resource.

#1 Best Overall
Amazon Kindle 16 GB (2024 model) - Light and compact, with fast page turns, and high contrast ratio - Matcha
  • Light and compact - With adjustable brightness, high contrast ratio, and fast page turns.
  • Effortless reading in any light - Read comfortably with a 6“ glare-free display, adjustable front light—now 25% brighter at max setting—and dark mode.
  • Escape into your books - Tune out messages, emails, and social media with a distraction-free reading experience.
  • Read for a while - Get up to 6 weeks of battery life on a single charge.
  • Take your library with you – 16 GB storage holds thousands of books.

Deployment steps in order

  1. Create the ECR repository with immutable tags. Immutable tags stop a published version from being silently overwritten.

    aws ecr create-repository --repository-name my-app --image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true --region us-east-1
  2. Build, tag and push a versioned image. Use a specific version such as 1.0.0 or a digest, not latest, in the task definition.

    aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com
    docker build -t my-app:1.0.0 .
    docker tag my-app:1.0.0 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:1.0.0
    docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:1.0.0
  3. Create the secret from a file. Passing the value on the command line leaves it in your shell history. Write the JSON to a file, create the secret, then delete the file.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    aws secretsmanager create-secret --name prod/my-app/db --secret-string file://db-secret.json --region us-east-1

    The command returns the secret ARN. Record it. The ARN ends in a random suffix, and you will need the full value for the task definition and the IAM policy.

    Rank #2
    Amazon Kindle 16 GB (2024 model) – Light and compact, with fast page turns, and high contrast ratio – Black
    • Light and compact - With adjustable brightness, high contrast ratio, and fast page turns.
    • Effortless reading in any light - Read comfortably with a 6“ glare-free display, adjustable front light—now 25% brighter at max setting—and dark mode.
    • Escape into your books - Tune out messages, emails, and social media with a distraction-free reading experience.
    • Read for a while - Get up to 6 weeks of battery life on a single charge.
    • Take your library with you - 16 GB storage holds thousands of books.
  4. Create the execution role and scope its secret access. Trust the ecs-tasks.amazonaws.com service principal, attach the managed execution policy, then add an inline policy like this one, using your own ARN:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "secretsmanager:GetSecretValue",
          "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/my-app/db-AbCdEf"
        }
      ]
    }

    If the secret is encrypted with a customer-managed KMS key, the role also needs decrypt permission on that key, and the key policy has to allow it. Confirm the exact key-policy statements in the AWS Secrets Manager and ECS documentation before you copy them into production. This walkthrough does not reproduce them.

  5. Register the task definition. The example below pins the image version, names both roles, sends logs to CloudWatch, and injects one key from the JSON secret as an environment variable. The valueFrom format is the secret ARN, followed by the JSON key name, then the version stage and version ID fields, which can be left empty to use the current version.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    {
      "family": "my-app",
      "requiresCompatibilities": ["FARGATE"],
      "networkMode": "awsvpc",
      "cpu": "512",
      "memory": "1024",
      "runtimePlatform": { "operatingSystemFamily": "LINUX", "cpuArchitecture": "X86_64" },
      "executionRoleArn": "arn:aws:iam::123456789012:role/my-app-execution-role",
      "taskRoleArn": "arn:aws:iam::123456789012:role/my-app-task-role",
      "containerDefinitions": [
        {
          "name": "my-app",
          "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:1.0.0",
          "essential": true,
          "portMappings": [{ "containerPort": 8080, "protocol": "tcp" }],
          "secrets": [
            { "name": "DB_PASSWORD", "valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/my-app/db-AbCdEf:password::" }
          ],
          "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
              "awslogs-group": "/ecs/my-app",
              "awslogs-region": "us-east-1",
              "awslogs-stream-prefix": "ecs"
            }
          }
        }
      ]
    }

    Omit taskRoleArn if the application makes no AWS API calls. Register the file with aws ecs register-task-definition --cli-input-json file://task-def.json.

  6. Create the cluster and service in private subnets. Disable the public IP so the task reaches ECR and Secrets Manager through the routes described in the networking section below.

    aws ecs create-cluster --cluster-name my-cluster --region us-east-1
    aws ecs create-service --cluster my-cluster --service-name my-app --task-definition my-app --desired-count 2 --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[subnet-aaa111,subnet-bbb222],securityGroups=[sg-0app123],assignPublicIp=DISABLED}" --region us-east-1
  7. Verify the deployment. Wait for the tasks to reach RUNNING, then check the service events and any stopped reasons. Confirm the application responds on its health endpoint through the path you intend to allow, and confirm that logs do not print the secret value. The verification checks are covered in more detail below.

    aws ecs describe-services --cluster my-cluster --services my-app --region us-east-1 --query "services[0].events[0:5]"
    aws ecs list-tasks --cluster my-cluster --service-name my-app --region us-east-1
    aws ecs describe-tasks --cluster my-cluster --tasks TASK_ARN --region us-east-1 --query "tasks[0].{status:lastStatus,stopped:stoppedReason}"
  8. Clean up tutorial resources. Scale the service to zero, delete it, delete the cluster, then remove the secret, repository, log group and roles you created for the exercise. Secret deletion has a recovery window unless you force deletion, and a forced deletion cannot be undone.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    aws ecs update-service --cluster my-cluster --service my-app --desired-count 0 --region us-east-1
    aws ecs delete-service --cluster my-cluster --service my-app --region us-east-1
    aws ecs delete-cluster --cluster my-cluster --region us-east-1
    aws secretsmanager delete-secret --secret-id prod/my-app/db --recovery-window-in-days 7 --region us-east-1
    aws ecr delete-repository --repository-name my-app --force --region us-east-1

Injecting secrets: environment variables or runtime retrieval

ECS can inject a Secrets Manager value into the container at startup, as shown in step 4. The alternative is to have the application call Secrets Manager itself with its task role. The two approaches move the risk to different places, so choose deliberately.

Rank #4
Amazon Kindle 16 GB (2024 model) – Light and compact, with fast page turns, and high contrast ratio – Without Lockscreen Ads – Black
  • The lightest and most compact Kindle - Now with a brighter front light at max setting, higher contrast ratio, and faster page turns for an enhanced reading experience.
  • Effortless reading in any light - Read comfortably with a 6“ glare-free display, adjustable front light—now 25% brighter at max setting—and dark mode.
  • Escape into your books - Tune out messages, emails, and social media with a distraction-free reading experience.
  • Read for a while - Get up to 6 weeks of battery life on a single charge.
  • Take your library with you - 16 GB storage holds thousands of books.
Question Startup injection through the task definition Application fetches the secret at runtime
Which role makes the retrieval The task execution role, by the ECS agent The task role, by application code
Where the value is visible To processes in the container and anyone who can read the environment, including diagnostic tools and any logging that dumps it In application memory once fetched, not in the task definition or the container environment
Rotation The value is fixed for the life of the task; a new value generally takes effect when tasks are replaced The application can re-read the secret and pick up a rotated value without a redeploy, if it is written to do so
Code changes None required beyond reading an environment variable The application needs an SDK call, caching and error handling

For most small services, startup injection is the simpler option, provided you treat the environment as sensitive: do not print it at startup, keep ecs execute-command access restricted, and do not echo environment dumps into logs. Full-secret and JSON-key or version-specific injection depend on the Fargate platform version and operating system you select. Check the ECS documentation on passing Secrets Manager secrets through environment variables and the sensitive-data tutorial for the requirements that apply to your configuration.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Network access: how the task reaches ECR and Secrets Manager

Each Fargate task runs in its own task elastic network interface (ENI) in the subnet you specify. The Fargate task networking documentation describes this model. Image pulls, log delivery and secret retrieval all need a network path from that ENI. With assignPublicIp=DISABLED, the task has no public address, so you must provide the path yourself, typically in one of two ways:

  • NAT gateway in a public subnet, with a route from the private subnet. This is simpler to set up and sends traffic to AWS services over the internet path through NAT.
  • Interface VPC endpoints for the services the task uses: ECR API and ECR Docker endpoints for image pulls, an S3 gateway endpoint because image layers are stored in S3, Secrets Manager, and CloudWatch Logs. This keeps traffic on the AWS network and removes the NAT dependency, but each endpoint has a cost and needs a security group that allows HTTPS from the task.

For Linux tasks on Fargate platform version 1.4.0, AWS documents that image pulls, log delivery and secret retrieval flow over the task ENI, and that this traffic is visible in VPC flow logs. Earlier platform versions have different ENI behavior, so confirm the platform version your service uses before relying on that specific behavior for troubleshooting. The ECR guidance for Amazon ECS lists the ECR permissions the execution role needs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Ingress rules

The service security group should allow inbound traffic only from the security group of the load balancer, or from a known client range, on the application port. The AWS getting-started guide uses an HTTP rule on port 80 open to 0.0.0.0/0 so that a tutorial task can be reached from a browser. That is an illustrative setting for a lab. Do not copy it into production, and do not open the task’s ports to the internet when a load balancer can front it.

Security boundaries

A container is not a security boundary between workloads. Amazon Web Services states in its Amazon ECS task IAM role guidance: “Containers are not a security boundary and the use of task IAM roles does not change this.” In practice, this means that containers in the same task share the task role and the injected secrets. Put workloads that trust each other in one task, and put workloads that need separate permissions in separate tasks with separate roles.

Verify and troubleshoot

A healthy deployment passes these checks:

  • The task status is RUNNING, and the service shows the desired number of healthy tasks.
  • The application’s health endpoint responds through the path you allowed, for example through the load balancer, and not through a path you did not intend to open.
  • Container logs contain no secret values. Search them once after the first start.
  • VPC flow logs, if enabled, show the expected traffic to ECR and Secrets Manager.

When a task fails, read the stopped reason from describe-tasks and the service events before changing anything else. The common failure patterns are these:

  • Image pull failure. The stopped reason mentions pulling the image. Check that the image tag exists, that the execution role has ECR pull permissions, and that the task can reach ECR, either through NAT or through the ECR endpoints.
  • Secret retrieval failure. The stopped reason typically starts with ResourceInitializationError and refers to secrets. Check the execution role’s inline policy against the exact secret ARN, confirm the JSON key name in valueFrom, and check KMS permissions if the secret uses a customer-managed key.
  • Task starts, then fails health checks. The application listens on a different port from containerPort, the security group blocks the load balancer, or the app needs a configured secret that it cannot read.
  • Secret value appears in logs. Stop the service, rotate the secret, remove the code path that prints the value, and redeploy with a new image version.

The tutorial covers verification of the running task, but it does not define health checks or operational tests for your application. Write those for your own service before you go live.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

Bestseller No. 1
Amazon Kindle 16 GB (2024 model) - Light and compact, with fast page turns, and high contrast ratio - Matcha
Amazon Kindle 16 GB (2024 model) - Light and compact, with fast page turns, and high contrast ratio - Matcha
Light and compact - With adjustable brightness, high contrast ratio, and fast page turns.; Read for a while - Get up to 6 weeks of battery life on a single charge.
$149.99
Bestseller No. 2
Amazon Kindle 16 GB (2024 model) – Light and compact, with fast page turns, and high contrast ratio – Black
Amazon Kindle 16 GB (2024 model) – Light and compact, with fast page turns, and high contrast ratio – Black
Light and compact - With adjustable brightness, high contrast ratio, and fast page turns.; Read for a while - Get up to 6 weeks of battery life on a single charge.
$149.99
Bestseller No. 4
Amazon Kindle 16 GB (2024 model) – Light and compact, with fast page turns, and high contrast ratio – Without Lockscreen Ads – Black
Amazon Kindle 16 GB (2024 model) – Light and compact, with fast page turns, and high contrast ratio – Without Lockscreen Ads – Black
Read for a while - Get up to 6 weeks of battery life on a single charge.; Take your library with you - 16 GB storage holds thousands of books.
$169.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.