Self-Host Dify on AWS with Terraform: ECS Fargate, Aurora PostgreSQL and ElastiCache

Illustration of Dify self-hosted on AWS with containers and a database

Written by

in

Dify’s own quick start is one command: clone the repository, run Docker Compose, open your browser. That gets you a demo in ten minutes — and a stack you cannot safely leave running for a real team. The Compose file runs about fifteen containers on one host, including PostgreSQL, Redis and the vector database, all with bundled default secrets, all gone if the host dies.

This guide builds the version I would actually hand to a client: Dify’s containers on ECS Fargate, its data in managed services (Aurora PostgreSQL, ElastiCache for Redis, S3 for files), everything defined in Terraform, with the decisions — and the bill — explained. I build and operate Dify on AWS for client work in Japan; this is the architecture I start from, and the notes include the parts that only show up after you have run it for a while.

A note on versions: Dify moves fast. This guide is written against the Dify 1.x line (the official Compose file referenced image tag 1.20.0 when this was written, in December 2026). The architecture does not depend on the minor version; the environment settings occasionally do, so check the current files under docker/envs/ in the Dify repository before you deploy — recent versions reorganised them.

What you will have at the end

Laptop showing the finished Dify web console and dashboard
  • Dify’s web console and API behind an Application Load Balancer with HTTPS, on your own domain
  • The Dify services (api, api_websocket, worker, worker_beat, web, plugin_daemon, sandbox) running as Fargate tasks you can scale independently
  • Aurora PostgreSQL Serverless v2 holding Dify’s application data, with automated backups and point-in-time recovery
  • ElastiCache for Redis as the Celery broker and cache
  • Uploaded files and knowledge-base documents in S3 instead of a container filesystem
  • All secrets in AWS Secrets Manager, none in the repository
  • The whole thing reproducible from Terraform: one apply to build, one destroy to remove

Why ECS Fargate (and when not to)

Diagram comparing AWS container options: EC2, ECS Fargate and EKS

Three container options are realistic on AWS, and the honest comparison is short.

EC2 with Docker Compose is the cheapest way to run Dify and the closest to the official guide. It is the right answer for a personal instance or a trial. Its limits are operational: one host is one point of failure, patching and backups are yours, and scaling means a bigger box.

ECS Fargate is the middle path this guide takes. No hosts to patch, each Dify service scales on its own, rolling deploys are built in, and the data tier moves to managed services where AWS handles backups and failover. You pay more than for a single EC2 instance; you buy back the operational work.

EKS only earns its complexity if your organisation already runs Kubernetes and wants Dify inside it. If you have to ask whether you need EKS for Dify, you do not.

The architecture, service by service

Dify is not one application. Its Compose stack has three groups, and the AWS design follows from keeping them straight.

Diagram of the Dify on AWS architecture: an Application Load Balancer in front of ECS Fargate services (web, api, api_websocket, worker, worker_beat, plugin_daemon, sandbox, Weaviate), backed by Aurora PostgreSQL, ElastiCache Redis and S3, with Secrets Manager, CloudWatch and Terraform as platform services.

Stateless Dify services — these become Fargate services, one task definition per role, sharing the same images as the Compose stack: api (the backend and console API), api_websocket (live workflow co-editing; an optional service enabled by the “collaboration” Compose profile), worker (Celery: document indexing, workflow jobs), worker_beat (the scheduler), web (the Next.js frontend), plugin_daemon (model and tool plugins), and sandbox (isolated execution for Code nodes). The sandbox deserves one caution: it runs user code, so it belongs in its own service with no route to anything except the API that calls it — do not co-locate it with the API task to save money.

Stateful dependencies — these leave the containers entirely. PostgreSQL becomes Aurora PostgreSQL Serverless v2 (Dify points at it with its normal DB settings). Redis becomes ElastiCache. File storage switches to S3 by setting Dify’s storage type to S3, so uploads and dataset files survive task replacement. The bundled Weaviate is the one dependency I usually keep as a container at first — a small dedicated Fargate service with EFS for its data — and move to a managed or external vector store only when the knowledge base grows; Dify also supports external vector databases through its VECTOR_STORE setting if you already run one.

Edge and platform — an ALB terminates HTTPS (ACM certificate) and routes console traffic to web and API paths to api. nginx, which fronts everything in the Compose stack, is no longer needed as a separate container; the ALB does its job. Secrets (database password, Redis auth, Dify’s SECRET_KEY, the sandbox and plugin-daemon keys) live in Secrets Manager and are injected into tasks. Logs go to CloudWatch Logs, one log group per service — when a workflow fails at 2 a.m., this is where you will live.

Networking follows the standard shape: public subnets only for the ALB, private subnets for tasks and data, and VPC endpoints (or a NAT gateway) for tasks to reach ECR, S3 and Secrets Manager. Budget note: a NAT gateway in every availability zone is a quiet, fixed monthly cost that surprises people; a single NAT for a small deployment, plus gateway endpoints for S3 and DynamoDB (which are free), is a reasonable economy — with the availability trade-off stated, not hidden.

The Terraform layout

Cloud infrastructure being built from Terraform modules

Keep it boring. One root module per environment, composed from small modules you will reuse for the next service you host:

  • network: VPC, subnets, endpoints, security groups (one per tier, chained by reference, no open database ports)
  • data: Aurora cluster (Serverless v2 scaling block, minimum 0.5 ACU), ElastiCache replication group, S3 bucket with versioning and encryption, EFS for Weaviate
  • platform: ECS cluster, task definitions and services per Dify role, ALB and listeners, ACM certificate, Secrets Manager entries, CloudWatch log groups and alarms
  • state: an S3 backend with DynamoDB locking, created once by hand (or by a bootstrap stack) before the first apply

Two practices matter more than the module structure. First, pin everything: the Terraform AWS provider, and the Dify image tags — never deploy latest for a platform whose upgrades occasionally include manual data steps (Dify’s 1.17 line, for example, required a staged Weaviate upgrade; a pinned tag is what turns that from an incident into a planned change). Second, treat the Dify environment variables as code: define them in the task definitions from variables and secrets, so a diff shows exactly what a deploy changes.

The Dify settings that actually matter

Dify settings panel with a key and configuration toggles

Most of Dify’s .env transfers directly to task environment variables. The ones people get wrong:

  • SECRET_KEY: generate a real random value, store it in Secrets Manager, and never change it casually — it signs sessions and encrypts stored credentials.
  • Database and Redis settings: point them at Aurora and ElastiCache endpoints, with TLS where the service requires it, and use a dedicated database and user for Dify.
  • Storage: switch the storage backend from local disk to S3 (the storage settings live in the env files) and give the task role permission to exactly one bucket. Leaving local storage on Fargate means uploads vanish on the next deploy.
  • Sandbox keys: the sandbox API key and the code-execution endpoint key must match between the api and sandbox services, and neither may be the bundled default. The same applies to the plugin daemon key. Every default secret in the Compose files is publicly known; replacing all of them is the single most important security step in this whole guide.
  • Web and console URLs: set Dify’s console, service API and web app base URLs to your HTTPS domain, or share links and OAuth callbacks will quietly point at the wrong place.

Deploying, in order

Stairs leading up to a cloud, showing the deployment steps in order
  1. Apply the network and data modules first, and note the endpoints Terraform outputs.
  2. Set the secret values in Secrets Manager (Terraform creates the entries; the values themselves are set out of band so they never touch state in plain text).
  3. Apply the platform module. The first run pulls images and starts services; the api service runs database migrations on boot.
  4. Watch the api service’s logs until migrations complete, then open the ALB address: Dify’s setup screen creates the first administrator account. Create it immediately — until you do, anyone who can reach the address can.
  5. Point your domain’s DNS at the ALB, confirm HTTPS, and only then open the security groups to your team’s addresses (or your VPN) if the console is not meant to be public.

First-boot checks that catch most problems: the worker service’s logs show it connecting to Redis and registering tasks; uploading a small document to a new knowledge base completes indexing (this exercises worker, S3, the vector store and your model provider key in one action); and a test workflow with a Code node returns a result (this exercises the sandbox path).

What it costs

Balance scale weighing cloud infrastructure against coins

Estimates, not quotes — AWS prices change and vary by region, so treat these as planning figures for a small production deployment in a major region (US East or Tokyo), checked against public AWS pricing in late 2026, and re-check the official pricing pages before you budget.

The always-on floor is roughly USD 120–200 per month before any real traffic: Aurora Serverless v2 at its 0.5 ACU minimum is about USD 44–55 of that (Tokyo is priced higher per ACU-hour than US regions), the ALB about USD 16–25, one NAT gateway about USD 32 plus data processing, ElastiCache’s smallest cache node roughly USD 12–25, and the Fargate services at minimum size (api, worker and web running continuously at small CPU/memory settings) the remainder. Model API usage (Bedrock or otherwise) is billed separately and, for a busy team, will exceed the infrastructure bill — that is normal, and a later article in this series will compare this architecture’s cost side by side with the EC2 and minimum setups.

The honest summary: you pay roughly the price of one good team lunch per month to not be your own database administrator, patcher and backup system. For a client-facing deployment that trade is easy; for a personal playground it is not — a single EC2 instance is the better fit.

Running it: the short list

Monitoring gauges with a heartbeat line for running Dify
  • Backups: Aurora’s automated backups with point-in-time recovery cover the database; the S3 bucket’s versioning covers files. Test a restore once, in the first month, or you do not have backups — you have a hope.
  • Alarms: alarm on worker queue depth (indexing silently backing up is the most common Dify production complaint), api 5xx at the ALB, and Aurora CPU/ACU saturation.
  • Scaling: worker is the service that scales with document and workflow load; api scales with console and API traffic; web barely moves. Scale them independently — that was the point of splitting them.
  • Upgrades: read the release notes, snapshot first, upgrade in a maintenance window, and check whether the vector store has its own migration step before you touch the Dify version. A later article in this series will set out the full procedure as a production upgrade checklist.

Failure modes worth knowing in advance

Magnifying glass inspecting a failed link in a service chain
  • Indexing stuck at “indexing” forever: almost always the worker cannot reach Redis, the vector store, or the model provider — in that order. Check worker logs before touching anything else.
  • Code nodes timing out: the api cannot reach the sandbox service, or the sandbox keys do not match between services.
  • Sessions dropping after a deploy: SECRET_KEY differs between api tasks or changed between versions.
  • Uploads disappearing: storage is still on local disk in a task somewhere — check the storage setting on every service that writes files, not just api.

Summary

Sunrise over the cloud setup with a checkmark

Run Dify’s services as services, and its data as managed data. ECS Fargate for the containers, Aurora PostgreSQL and ElastiCache for the state Dify cannot afford to lose, S3 for files, Secrets Manager for the keys, Terraform for all of it — pinned, diffed and reproducible. The Compose stack is a brilliant demo and a fine personal setup; this is what it grows into when a team depends on it.

Coming next in this series (in preparation): Dify on EC2 with Docker Compose — the cheapest production-viable setup; What Dify on AWS Actually Costs, a three-architecture comparison; and a guide to connecting Dify to Amazon Bedrock as your model provider.