How can I run an Amazon ECS task on Fargate in a private subnet?

Last updated: 2022-07-15

I want to run an Amazon Elastic Container Service (Amazon ECS) task on AWS Fargate in a private subnet.

Short description

You can run Fargate tasks in private subnets. However, based on your use case, you might require internet access for certain operations, such as pulling an image from a public repository. Or, you might want to prevent any internet access for your tasks.

To run Fargate tasks in a private subnet without internet access, use VPC endpoints. VPC endpoints allow you to run Fargate tasks without granting the tasks access to the internet. The required endpoints are accessed over a private IP address.

If you need your task to access the internet from a private subnet, grant internet access using a NAT Gateway. The required endpoints are accessed over the public IP address of the NAT gateway.

Resolution

Create a VPC

Create an Amazon Virtual Private Cloud (Amazon VPC) with public or private subnets.

Then, depending on your use case, follow the steps in Use a private subnet without internet access (VPC endpoints method) or Use a Private subnet with internet access sections of this article.

Use a private subnet without internet access (VPC endpoints method)

To create interface endpoints and an S3 gateway:

  1. Create an S3 gateway endpoint.
  2. Create ECR interface endpoints.
  3. If your task uses Secrets Manager to inject secrets into the task and CloudWatch Logs, create interface endpoints for Secrets Manager and CloudWatch Logs.

Then, follow the instructions in the Create an Amazon ECS cluster and service section of this article.

Use a private subnet with internet access

Create a NAT gateway.

When you create your NAT gateway, be sure that you:

  • Place your NAT gateway inside the public subnet.
  • Update the route table of the private subnet. For Destination, enter 0.0.0.0/0. For Target, select the ID of your NAT gateway.

Then, follow the instructions in the Create an Amazon ECS cluster and service section of this article.

Create an Amazon ECS cluster and service

  1. Create an Amazon ECS cluster using the Networking only template (powered by Fargate).
  2. Create an Amazon ECS service.

When you configure the network for the service, be sure that you:

  1. Choose the cluster that you created in step 1 for your cluster VPC.
  2. Based on the method that you chose earlier, choose the private subnet that you configured for the VPC endpoints, or the subnet that you configured for the NAT gateway.

Now, your new tasks will launch in the private subnet.


Did this article help?


Do you need billing or technical support?