Guide · AWS Cloud Map · ECS Integration
AWS Cloud Map ECS Integration for MCP Server Deployments — serviceRegistries, Task Definitions, and ECS Service Connect
ECS's Cloud Map integration automates service registration and deregistration: when a task starts, ECS calls RegisterInstance and sets the instance to HEALTHY; when the task stops, ECS calls DeregisterInstance — all without any application code changes. The integration is configured via the serviceRegistries field in the ECS service definition and requires the ECS service-linked role to have servicediscovery:* access to the target Cloud Map service. This guide covers the serviceRegistries configuration, containerPort vs portMappingName registration modes, health check grace period for slow-starting MCP servers, and when to use Cloud Map DNS integration vs ECS Service Connect. For namespace and service setup, see Cloud Map Overview. For manual registration patterns, see Service Registration and Instances. For discovery patterns, see Cloud Map DiscoverInstances.
TL;DR
Add serviceRegistries to your ECS CreateService or UpdateService call with the Cloud Map service ARN. For Fargate tasks in awsvpc networking mode (the standard for MCP servers), set containerName and containerPort to tell ECS which container's IP and port to register. ECS uses the task ENI's private IP as AWS_INSTANCE_IPV4 and the mapped port as AWS_INSTANCE_PORT. Set healthCheckGracePeriodSeconds on the ECS service to cover the time your MCP server takes to initialize and pass its first health check — without this, ECS may kill tasks that are still starting up. Cloud Map DNS integration gives you a simple service-name.namespace.local hostname; ECS Service Connect gives you mTLS and traffic observability via App Mesh proxies.
How ECS Cloud Map integration works
When you configure serviceRegistries in an ECS service definition, the ECS service scheduler takes responsibility for Cloud Map lifecycle management. The lifecycle is:
- ECS launches a new task. The task starts and enters the
RUNNINGstate. - ECS calls
RegisterInstanceagainst the Cloud Map service specified inserviceRegistries.registryArn, using the task ENI's private IP asAWS_INSTANCE_IPV4and the mapped container port asAWS_INSTANCE_PORT. - If the Cloud Map service has
HealthCheckCustomConfig, the instance is initially inUNKNOWNhealth status. ECS waits for the container health check to pass, then callsUpdateInstanceCustomHealthStatus(HEALTHY). - The instance appears in DNS and
DiscoverInstancesresults after the health status is set to HEALTHY and the DNS change propagates. - When a task is stopped (scale-in, deployment, or failure), ECS calls
DeregisterInstanceand waits for the DNS record to be removed before the task is terminated.
This automatic lifecycle management is the primary reason to use ECS's Cloud Map integration rather than calling the Cloud Map SDK from your application code — ECS handles race conditions, retries, and cleanup correctly even when tasks are stopped unexpectedly due to OOM kills or infrastructure failures.
serviceRegistries in ECS service definitions
import {
ECSClient,
CreateServiceCommand,
type CreateServiceCommandInput,
type ServiceRegistry,
} from "@aws-sdk/client-ecs";
const ecs = new ECSClient({ region: "us-east-1" });
async function createMcpServerEcsService(params: {
clusterArn: string;
taskDefinitionArn: string;
cloudMapServiceArn: string; // Cloud Map service ARN, NOT service ID
subnetIds: string[];
securityGroupIds: string[];
containerName: string; // must match containerDefinitions[].name
containerPort: number; // must match containerDefinitions[].portMappings[].containerPort
}): Promise<void> {
// serviceRegistries entry — tells ECS how to register tasks in Cloud Map
const serviceRegistry: ServiceRegistry = {
registryArn: params.cloudMapServiceArn, // Cloud Map service ARN
containerName: params.containerName, // which container's IP/port to register
containerPort: params.containerPort, // which port mapping to register
// port: 3000 // only used for CNAME or SRV records with non-standard ports
};
const input: CreateServiceCommandInput = {
cluster: params.clusterArn,
serviceName: "mcp-server",
taskDefinition: params.taskDefinitionArn,
desiredCount: 2,
launchType: "FARGATE",
// Service Connect OR serviceRegistries — not both simultaneously
// (ECS Service Connect manages its own Cloud Map resources internally)
serviceRegistries: [serviceRegistry],
networkConfiguration: {
awsvpcConfiguration: {
subnets: params.subnetIds,
securityGroups: params.securityGroupIds,
assignPublicIp: "DISABLED", // private subnets for MCP servers
},
},
// CRITICAL for Cloud Map integration: grace period covers MCP server startup
// time before the first health check is evaluated.
// Without this, ECS kills tasks that haven't finished initializing yet.
// Set to: max startup time + container health check interval + buffer
healthCheckGracePeriodSeconds: 120, // 2 minutes for MCP servers with slow init
deploymentConfiguration: {
minimumHealthyPercent: 100, // never scale below current healthy count
maximumPercent: 200, // allow double capacity during rolling deploy
},
};
await ecs.send(new CreateServiceCommand(input));
}
The registryArn must be the full Cloud Map service ARN, not the service ID. The ARN format is arn:aws:servicediscovery:REGION:ACCOUNT:service/srv-XXXXXXXX. You can retrieve it from the Service.Arn field returned by CreateService or GetService in the Cloud Map SDK.
The containerName and containerPort tell ECS which container and port mapping to use when constructing the Cloud Map instance attributes. For Fargate tasks in awsvpc mode, every container gets the task ENI's IP; containerName + containerPort identifies which port to register as AWS_INSTANCE_PORT. If your MCP server task definition has only one container and one port mapping, you can omit these and ECS will use the single port automatically.
Task definition with awsvpc networking and port mappings
import {
RegisterTaskDefinitionCommand,
type RegisterTaskDefinitionCommandInput,
} from "@aws-sdk/client-ecs";
const taskDef: RegisterTaskDefinitionCommandInput = {
family: "mcp-server",
networkMode: "awsvpc", // required for Fargate; Cloud Map uses task ENI IP
requiresCompatibilities: ["FARGATE"],
cpu: "512",
memory: "1024",
executionRoleArn: "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
taskRoleArn: "arn:aws:iam::123456789012:role/mcpServerTaskRole",
containerDefinitions: [
{
name: "mcp-server", // matches serviceRegistries.containerName
image: "123456789012.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest",
essential: true,
portMappings: [
{
containerPort: 3000, // matches serviceRegistries.containerPort
hostPort: 3000, // must match containerPort in awsvpc mode
protocol: "tcp",
// name: "mcp-http" // optional name — required for ECS Service Connect
},
],
healthCheck: {
command: ["CMD-SHELL", "curl -sf http://localhost:3000/health || exit 1"],
interval: 30, // seconds between checks
timeout: 10, // seconds to wait for the health check command
retries: 3, // consecutive failures to mark unhealthy
startPeriod: 60, // grace period before checks start (covers slow startup)
},
environment: [
{ name: "PORT", value: "3000" },
{ name: "NODE_ENV", value: "production" },
],
logConfiguration: {
logDriver: "awslogs",
options: {
"awslogs-group": "/ecs/mcp-server",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "mcp-server",
"awslogs-create-group": "true",
},
},
},
],
};
await ecs.send(new RegisterTaskDefinitionCommand(taskDef));
The container healthCheck is the signal ECS uses to call UpdateInstanceCustomHealthStatus(HEALTHY) in Cloud Map. Without a container health check defined, ECS considers the task healthy immediately after it reaches RUNNING state and registers it as HEALTHY in Cloud Map without waiting for the application to be ready. For MCP servers that take several seconds to initialize (loading tool schemas, establishing database connections, downloading model weights), always define a container health check.
healthCheckGracePeriodSeconds: the most common misconfiguration
The ECS service's healthCheckGracePeriodSeconds is different from the container's healthCheck.startPeriod. The startPeriod is a grace period before the container health check starts counting failures — it prevents premature restarts during cold start. The healthCheckGracePeriodSeconds is a grace period for the ECS service's ALB target group health checks (or Cloud Map health checks) before ECS acts on unhealthy status.
For Cloud Map integration specifically, healthCheckGracePeriodSeconds controls how long ECS waits after a task reaches RUNNING before it starts evaluating Cloud Map health status. If a task starts, registers with Cloud Map, but Cloud Map marks it UNHEALTHY (because the custom health check hasn't been called yet), ECS may replace the task unless the grace period covers the startup window.
// Calculate healthCheckGracePeriodSeconds:
// = container startPeriod (from task def healthCheck)
// + healthCheck.interval * healthCheck.retries (worst case)
// + network warm-up buffer
//
// Example for an MCP server with:
// startPeriod: 60s
// interval: 30s
// retries: 3
// worst case health check time = 60 + (30 * 3) = 150s
// add 30s buffer = 180s healthCheckGracePeriodSeconds
//
// In practice: set healthCheckGracePeriodSeconds = 120-180s for MCP servers
// that connect to external services (databases, vector stores, model APIs)
// during initialization.
const serviceConfig = {
healthCheckGracePeriodSeconds: 180,
// ...other service config
};
Setting healthCheckGracePeriodSeconds too low is the most common cause of "ECS tasks keep restarting during deployment" with Cloud Map integration. The symptom is a cycle: ECS deploys a new task, the task starts successfully and passes its container health check, but ECS replaces it again because the Cloud Map health status was UNKNOWN or UNHEALTHY during the grace period window.
Cloud Map DNS integration vs ECS Service Connect
ECS offers two service-to-service discovery mechanisms: Cloud Map DNS integration (via serviceRegistries) and ECS Service Connect. Both use Cloud Map under the hood, but they have different operational models:
| Cloud Map DNS integration | ECS Service Connect | |
|---|---|---|
| Configuration | serviceRegistries in ECS service |
serviceConnectConfiguration in ECS service |
| Discovery mechanism | DNS A records + DiscoverInstances |
Envoy proxy sidecar intercepts traffic |
| Load balancing | Client-side DNS round-robin (up to 8 instances) | Proxy-side, full pool visibility |
| mTLS | Not included — handle at application layer | Optional TLS termination at Envoy |
| Traffic metrics | Via CloudWatch Container Insights only | Detailed per-route metrics via App Mesh |
| Retries & circuit breaking | Client must implement | Envoy handles retries and circuit breaking |
| SSE/WebSocket support | Full support — DNS routes to instance IP directly | Supported via Envoy HTTP/1.1 or HTTP/2 upgrade |
| Setup complexity | Low — single serviceRegistries field |
Medium — namespace, client/server port configs |
| Cost overhead | Cloud Map namespace + instance charges only | Envoy sidecar CPU/memory per task (extra cost) |
For MCP servers, Cloud Map DNS integration is the simpler starting point. ECS Service Connect adds value when you need connection-level observability (request rate, error rate, p99 latency per route) across a mesh of MCP server microservices. For a single MCP server service behind an ALB, Cloud Map DNS integration is sufficient and avoids the Envoy sidecar overhead.
Retrieving registered instance details from a running ECS task
To know which Cloud Map instance ID to use in health status updates or manual deregistration from within an ECS Fargate task, retrieve the task ARN from the ECS container metadata endpoint:
// Get ECS task metadata from within a running Fargate task
async function getEcsTaskMetadata(): Promise<{
taskArn: string;
privateIp: string;
}> {
const metadataUri = process.env.ECS_CONTAINER_METADATA_URI_V4;
if (!metadataUri) throw new Error("Not running in ECS");
// GET /task returns the task-level metadata
const response = await fetch(`${metadataUri}/task`);
const metadata = await response.json();
// TaskARN: "arn:aws:ecs:us-east-1:123456789012:task/cluster/TASK_ID"
const taskArn = metadata.TaskARN as string;
// Extract the task's private IP from container network interfaces
const container = metadata.Containers[0];
const networkInterface = container.Networks[0];
const privateIp = networkInterface.IPv4Addresses[0];
return { taskArn, privateIp };
}
// Use the task ARN as the Cloud Map InstanceId — it's stable and unique
const { taskArn, privateIp } = await getEcsTaskMetadata();
await registerMcpServerInstance(cloudMapServiceId, privateIp, 3000, taskArn);
The ECS task ARN is the natural Cloud Map instance ID: it is unique across all tasks in an account and region, stable for the task's lifetime, and already used by ECS internally when it auto-registers. If you need to call UpdateInstanceCustomHealthStatus from your application rather than relying on ECS's container health check integration, use the task ARN as the instance ID to match what ECS registered.
Deployment: rolling updates with Cloud Map
During a rolling deployment of an MCP server ECS service, Cloud Map keeps the registry accurate as old tasks are replaced by new ones:
- ECS launches new tasks (up to
maximumPercentofdesiredCount). - New tasks register with Cloud Map; ECS waits for them to pass container health checks before marking them HEALTHY in Cloud Map.
- Once new tasks are HEALTHY in Cloud Map, DNS clients resolve to both old and new instance IPs (MULTIVALUE returns up to 8 total).
- ECS stops old tasks (down to
minimumHealthyPercentofdesiredCount). - ECS deregisters old task instances from Cloud Map. DNS records update after the Route 53 change propagates.
MCP server deployments using SSE transport need special care during this process: existing SSE sessions on old tasks persist until the client disconnects or the session times out. Configure minimumHealthyPercent: 100 to ensure the number of healthy instances never drops below desiredCount during the deployment, so there is always enough capacity to handle incoming connections while old sessions drain.
Use AliveMCP to monitor the /health endpoint of your ECS service's target group during rolling deployments — it provides an external view of availability that complements ECS's internal health reporting and Cloud Map's instance health status.