Deploy Next.js to AWS with Docker Compose
Learn how to deploy a Next.js application to AWS ECS using Docker Compose and Defang. Complete with database and caching.
Deploy Next.js to AWS with Docker Compose
In this tutorial, you’ll deploy a Next.js application to AWS using the same Docker Compose workflow you use locally. Write a compose.yaml, test it with docker compose up, then deploy it to production AWS with one command.
Prerequisites
Before starting, make sure you have:
- Docker Desktop installed
- Defang CLI installed (
brew install defang-io/defang/defang) - An AWS account connected to Defang
Step 1: Create your Next.js app
If you don’t already have a Next.js app, create one:
npx create-next-app@latest my-app
cd my-app
Step 2: Create a Dockerfile
Create a Dockerfile in your project root:
FROM node:20-alpine AS base
FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
EXPOSE 3000
CMD ["node", "server.js"]
Step 3: Create compose.yaml
Create a compose.yaml file. This is a standard Docker Compose file — nothing Defang-specific except the x-defang-postgres annotation for managed database provisioning:
services:
web:
build: .
ports:
- "3000:3000"
environment:
- DATABASE_URL
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000"]
interval: 30s
timeout: 10s
retries: 3
db:
x-defang-postgres: true
Test it locally first with docker compose up to make sure everything works. (For local dev, you can use a standard postgres:16 image instead of the x-defang-postgres annotation.)
Step 4: Deploy to AWS
The same Docker Compose file you just tested locally deploys directly to AWS:
defang compose up --provider=aws
Defang will:
- Build your Next.js Docker image
- Push it to AWS ECR
- Create an ECS cluster with Fargate
- Provision an RDS PostgreSQL database
- Set up an Application Load Balancer
- Configure networking and security groups
Step 5: Verify deployment
Check your running services:
defang services
You’ll see a table with your service endpoints. Open the endpoint URL in your browser to see your app.
Next steps
- Add a custom domain with
defang cert generate - Set up CI/CD with GitHub Actions
- Add Redis caching with
x-defang-redis: true - Add MongoDB with
x-defang-mongodb: truefor DocumentDB - Add managed LLMs with
x-defang-llm: truefor AWS Bedrock - Create dev/staging/prod environments with
defang stack new - Deploy from your IDE with
defang mcp setup --client=vscode