Guide · Amazon EFS · Amazon ECS · Fargate · Persistent Storage
Amazon EFS with ECS and Fargate for MCP Servers — Persistent Volumes for Stateful Containers
ECS and Fargate containers are ephemeral by default — the local filesystem inside a task is destroyed when the task stops. For MCP servers that need to persist state across task restarts (session context files, shared model caches, generated artifacts), Amazon EFS provides a persistent NFS volume that survives task replacement. Multiple tasks in the same ECS service can mount the same EFS access point simultaneously, enabling shared reads and coordinated writes. This guide covers the complete ECS + EFS integration: task definition volume configuration, security group chain, IAM authorization, Fargate platform version requirements, access point isolation between services, and patterns for stateful MCP server containers.
TL;DR
Add an EFS volume to an ECS task definition: set volumes[].efsVolumeConfiguration.fileSystemId, authorizationConfig.accessPointId, and transitEncryption: "ENABLED". Mount it in the container via mountPoints referencing the volume name. The Fargate task SG needs outbound TCP 2049; the EFS SG needs inbound TCP 2049 from the task SG. The task execution role (not the task role) needs elasticfilesystem:ClientMount. Fargate platform version 1.4 or later is required — do NOT use LATEST in regions where LATEST still maps to 1.3.
Why EFS for ECS-based MCP servers
ECS Fargate tasks are stateless by design. When a task fails health checks, ECS stops it and starts a replacement. Any data written to the container's local filesystem is lost. For MCP servers, this creates three common problems:
- Shared model cache — if each task independently downloads a large embedding model from S3 on startup, task replacements (from ECS service autoscaling or failures) add minutes to recovery time. EFS persists the cache across task lifecycles.
- Session state — MCP servers that maintain conversation context in files lose state on task restart unless that state is externalized. EFS provides a simple file-based session store that survives task replacement; for high-concurrency needs, combine with DynamoDB for metadata.
- Tool artifact sharing — when one MCP tool generates a file (PDF, rendered chart, compiled document) and a second tool needs to consume it in the same session, EFS provides a shared workspace without an S3 round-trip.
EFS is the right choice when you need POSIX file semantics. If you need key-value data, use DynamoDB or ElastiCache. If you need large binary blobs with version history, use S3. EFS excels when your code naturally uses fs.readFile / fs.writeFile patterns and you want to extend those patterns across multiple container instances.
Fargate platform version requirement
EFS volumes in ECS Fargate tasks require platform version 1.4 or later. Earlier versions do not support EFS. The LATEST platform version alias maps to different actual versions in different regions and may still point to 1.3 in some older regions — explicitly specify 1.4 rather than relying on LATEST.
# ECS service config — always specify platformVersion explicitly
aws ecs create-service \
--cluster mcp-cluster \
--service-name mcp-server \
--task-definition mcp-server-task:5 \
--desired-count 2 \
--launch-type FARGATE \
--platform-version 1.4 \ # explicit — do NOT use LATEST
--network-configuration "awsvpcConfiguration={
subnets=[subnet-aaa111,subnet-bbb222],
securityGroups=[sg-fargate-mcp],
assignPublicIp=DISABLED
}"
To check the platform version on a running service:
aws ecs describe-services \
--cluster mcp-cluster \
--services mcp-server \
--query 'services[0].platformVersion'
If you have an existing service on platform version 1.3, you must delete and recreate the service (or update and force a new deployment) to migrate to 1.4. Services do not upgrade platform version in-place.
Security group chain
The Fargate task and the EFS mount target must be in the same VPC. The task's security group must allow outbound TCP 2049 (NFS) to the EFS security group, and the EFS security group must allow inbound TCP 2049 from the task security group.
# Create EFS security group
aws ec2 create-security-group \
--group-name efs-ecs-sg \
--description "EFS: inbound NFS from ECS Fargate tasks" \
--vpc-id vpc-12345678
# Create Fargate task security group
aws ec2 create-security-group \
--group-name fargate-mcp-sg \
--description "Fargate MCP server tasks" \
--vpc-id vpc-12345678
# EFS SG: allow inbound NFS from Fargate task SG
aws ec2 authorize-security-group-ingress \
--group-id sg-efs-ecs \
--protocol tcp \
--port 2049 \
--source-group sg-fargate-mcp
# Fargate task SG: allow outbound NFS to EFS SG
# (default all-egress usually covers this, but if restricted:)
aws ec2 authorize-security-group-egress \
--group-id sg-fargate-mcp \
--protocol tcp \
--port 2049 \
--destination-group sg-efs-ecs
# Task also needs outbound HTTPS (443) for AWS API calls
aws ec2 authorize-security-group-egress \
--group-id sg-fargate-mcp \
--protocol tcp \
--port 443 \
--cidr 0.0.0.0/0
The error ResourceInitializationError: failed to invoke EFS utils commands to set up EFS volumes: timeout waiting for NFS in ECS task stop reason almost always indicates a broken security group chain. Check both directions: outbound on the task SG and inbound on the EFS SG.
Task definition — volume configuration
The EFS volume is defined in the volumes section of the task definition and referenced by name in the container's mountPoints. Use the IAM authorization config with an access point for per-service isolation:
import { ECSClient, RegisterTaskDefinitionCommand } from "@aws-sdk/client-ecs";
const ecs = new ECSClient({ region: "us-east-1" });
const { taskDefinition } = await ecs.send(new RegisterTaskDefinitionCommand({
family: "mcp-server-task",
networkMode: "awsvpc", // required for Fargate
requiresCompatibilities: ["FARGATE"],
cpu: "512",
memory: "1024",
executionRoleArn: "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
taskRoleArn: "arn:aws:iam::123456789012:role/mcp-server-task-role",
// Define the EFS volume
volumes: [
{
name: "mcp-shared-data", // referenced in mountPoints below
efsVolumeConfiguration: {
fileSystemId: "fs-0abc123def456",
transitEncryption: "ENABLED", // TLS in transit (recommended)
authorizationConfig: {
accessPointId: "fsap-0xyz789", // access point for this service
iam: "ENABLED", // enforce IAM auth (ClientMount check)
},
},
},
],
containerDefinitions: [
{
name: "mcp-server",
image: "123456789012.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest",
portMappings: [{ containerPort: 3000, protocol: "tcp" }],
// Mount the EFS volume at /data inside the container
mountPoints: [
{
sourceVolume: "mcp-shared-data", // matches volumes[].name above
containerPath: "/data", // path inside container
readOnly: false, // set true for read-only mounts
},
],
logConfiguration: {
logDriver: "awslogs",
options: {
"awslogs-group": "/ecs/mcp-server",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs",
},
},
healthCheck: {
command: ["CMD-SHELL", "curl -f http://localhost:3000/health || exit 1"],
interval: 30,
timeout: 5,
retries: 3,
startPeriod: 10,
},
},
],
}));
console.log("Registered task definition:", taskDefinition?.taskDefinitionArn);
The transitEncryption: "ENABLED" field tells ECS to mount EFS with TLS (the equivalent of -o tls on EC2). Without this, NFS traffic is unencrypted on the wire. When iam: "ENABLED" is set, ECS passes IAM credentials to the EFS mount helper, which verifies the task execution role has elasticfilesystem:ClientMount.
IAM — task execution role vs task role
EFS IAM authorization in ECS requires the permission on the task execution role (the role ECS itself uses to set up the task infrastructure, including mounting EFS), not the task role (the role the application code uses to call AWS APIs).
# Task EXECUTION role policy — ECS uses this to mount EFS
# Attach to: arn:aws:iam::123456789012:role/ecsTaskExecutionRole
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "EFSMount",
"Effect": "Allow",
"Action": [
"elasticfilesystem:ClientMount" # read-only mount
],
"Resource": "arn:aws:elasticfilesystem:us-east-1:123456789012:file-system/fs-0abc123def456",
"Condition": {
"StringEquals": {
"elasticfilesystem:AccessPointArn":
"arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-0xyz789"
}
}
}
]
}
# For a read-write mount, also add ClientWrite:
{
"Sid": "EFSMountWrite",
"Effect": "Allow",
"Action": [
"elasticfilesystem:ClientMount",
"elasticfilesystem:ClientWrite"
],
"Resource": "arn:aws:elasticfilesystem:us-east-1:123456789012:file-system/fs-0abc123def456",
"Condition": {
"StringEquals": {
"elasticfilesystem:AccessPointArn":
"arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-0xyz789"
}
}
}
The execution role also needs the standard ECS permissions (ecr:GetAuthorizationToken, ecr:BatchGetImage, logs:CreateLogStream, etc.) — these are included in AmazonECSTaskExecutionRolePolicy. Add the EFS statement as an inline policy on the existing execution role rather than replacing the managed policy.
The task role (application runtime permissions) is separate. If your MCP server Node.js code calls the EFS API directly (e.g., to describe access points), the task role needs those API permissions. For simple file I/O via the fs module, the task role does not need any EFS permissions — only the execution role does.
Access point isolation — one per ECS service
When multiple ECS services share one EFS file system, use a separate access point per service with distinct directory paths and POSIX UID/GID assignments. This prevents one service from reading or overwriting another service's data at the NFS level.
import { EFSClient, CreateAccessPointCommand } from "@aws-sdk/client-efs";
const efs = new EFSClient({ region: "us-east-1" });
// Access point for the MCP server service (UID 1000)
const { AccessPointId: mcpApId } = await efs.send(new CreateAccessPointCommand({
FileSystemId: "fs-0abc123def456",
PosixUser: { Uid: 1000, Gid: 1000 },
RootDirectory: {
Path: "/services/mcp-server",
CreationInfo: { OwnerUid: 1000, OwnerGid: 1000, Permissions: "755" },
},
Tags: [{ Key: "Service", Value: "mcp-server" }],
}));
// Access point for a data-pipeline sidecar service (UID 2000, writes models)
const { AccessPointId: pipelineApId } = await efs.send(new CreateAccessPointCommand({
FileSystemId: "fs-0abc123def456",
PosixUser: { Uid: 2000, Gid: 2000 },
RootDirectory: {
Path: "/services/data-pipeline",
CreationInfo: { OwnerUid: 2000, OwnerGid: 2000, Permissions: "755" },
},
Tags: [{ Key: "Service", Value: "data-pipeline" }],
}));
// Cross-service read: if mcp-server needs to read data-pipeline output,
// create a third access point pointing at a shared output directory:
const { AccessPointId: sharedApId } = await efs.send(new CreateAccessPointCommand({
FileSystemId: "fs-0abc123def456",
PosixUser: { Uid: 1000, Gid: 1000 }, // readable by mcp-server UID
RootDirectory: {
Path: "/shared/models", // pipeline writes here; mcp-server reads here
CreationInfo: { OwnerUid: 2000, OwnerGid: 1000, Permissions: "775" }, // group-writable
},
Tags: [{ Key: "Purpose", Value: "shared-models" }],
}));
The pattern of one access point per service with its own directory path means you can inspect each service's data independently, apply different IAM policies per access point, and avoid one service's runaway writes filling the shared file system to the detriment of other services.
Multiple volumes in one task definition
An ECS task can mount multiple EFS volumes from different file systems or different access points on the same file system. Use multiple entries in the volumes and mountPoints arrays:
volumes: [
{
name: "mcp-models",
efsVolumeConfiguration: {
fileSystemId: "fs-0abc123def456",
transitEncryption: "ENABLED",
authorizationConfig: {
accessPointId: "fsap-models111", // read-only models directory
iam: "ENABLED",
},
},
},
{
name: "mcp-sessions",
efsVolumeConfiguration: {
fileSystemId: "fs-0abc123def456", // same file system, different access point
transitEncryption: "ENABLED",
authorizationConfig: {
accessPointId: "fsap-sessions222", // read-write sessions directory
iam: "ENABLED",
},
},
},
],
containerDefinitions: [{
name: "mcp-server",
mountPoints: [
{
sourceVolume: "mcp-models",
containerPath: "/data/models",
readOnly: true, // models are read-only for the MCP server
},
{
sourceVolume: "mcp-sessions",
containerPath: "/data/sessions",
readOnly: false, // sessions are read-write
},
],
// ...
}]
The execution role needs ClientMount on each access point ARN. Use separate Condition blocks or a list of ARNs in the resource field:
{
"Sid": "EFSMountMultiple",
"Effect": "Allow",
"Action": ["elasticfilesystem:ClientMount", "elasticfilesystem:ClientWrite"],
"Resource": "arn:aws:elasticfilesystem:us-east-1:123456789012:file-system/fs-0abc123def456",
"Condition": {
"StringLike": {
"elasticfilesystem:AccessPointArn": [
"arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-models111",
"arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-sessions222"
]
}
}
}
Startup order — health check and EFS readiness
ECS does not guarantee that the EFS mount is fully available before the container's entrypoint runs. In practice the mount is ready within a few seconds, but during task start the NFS mount handshake is happening in parallel with container initialization. If your application reads from EFS at startup (e.g., loading a model in module-level code), add a startup retry loop:
// startup.ts — called at module load before accepting requests
import fs from "fs";
import path from "path";
const MOUNT_PATH = "/data/models";
const MAX_RETRIES = 10;
const RETRY_INTERVAL_MS = 1000;
async function waitForEFSMount(): Promise<void> {
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
// EFS is ready when we can stat the mount point directory
fs.statSync(MOUNT_PATH);
console.log(`EFS mount ready at ${MOUNT_PATH} (attempt ${attempt})`);
return;
} catch (err) {
if (attempt === MAX_RETRIES) {
throw new Error(
`EFS mount at ${MOUNT_PATH} not ready after ${MAX_RETRIES}s — check security group and mount target`
);
}
console.warn(`EFS mount not ready, retrying in ${RETRY_INTERVAL_MS}ms (attempt ${attempt}/${MAX_RETRIES})`);
await new Promise(r => setTimeout(r, RETRY_INTERVAL_MS));
}
}
}
export async function initializeServer(): Promise<void> {
await waitForEFSMount();
// Now safe to read models, session files, etc.
}
Set the ECS health check startPeriod to at least 15 seconds to give the container time to complete the EFS mount and application initialization before ECS starts evaluating health check results. Without a sufficient start period, ECS may kill and restart the task before it finishes mounting EFS — creating a restart loop.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
ResourceInitializationError: timeout waiting for NFS mount | Security group chain broken (most common); EFS mount target not in same VPC; mount target not available | Verify: Fargate task SG has outbound TCP 2049 → EFS SG; EFS SG has inbound TCP 2049 from task SG; both in same VPC; mount target status is available |
ResourceInitializationError: EFS volume requires platform version 1.4 | Service configured with platform version LATEST which resolved to 1.3 in this region | Explicitly set platformVersion: "1.4" on the ECS service |
AccessDeniedException from EFS | Task execution role missing elasticfilesystem:ClientMount | Add ClientMount to the task execution role (ecsTaskExecutionRole), not the task role; scope to the access point ARN via Condition |
EACCES: permission denied inside container | Container process UID does not match access point PosixUser.Uid; or ClientWrite missing for writes | Align Dockerfile USER UID with access point PosixUser.Uid; add ClientWrite for write mounts |
| Files from one service visible to another | Both services using same access point or root mount | Create a separate access point per service with distinct RootDirectory paths |
| High task startup time after ECS deployment | EFS mount handshake adds ~200–500 ms to task initialization; first read of large model from EFS adds additional latency | Use ECS Deployment Circuit Breaker with rollback; set healthCheck startPeriod to accommodate startup time; consider EFS One Zone for lower latency within single AZ |
Related guides
- Amazon EFS for MCP servers: fundamentals, mount targets, and access points
- EFS with Lambda: mounting shared file systems in serverless MCP server functions
- EFS performance modes and throughput: Bursting, Elastic, and Provisioned for MCP servers
- Amazon ECS for MCP servers: Fargate service deployment and task configuration
- ECS Deployment Circuit Breaker for MCP servers: automatic rollback on failed deployments
- MCP server uptime monitoring