2023-10-02 13:25:42+00:00

Developing serverless applications that query AWS resources (like DynamoDB or SQS) can be slow and expensive if you connect to real cloud resources during daily development. You have to handle network latency, manage IAM credentials, and incur minor AWS costs for every query execution.

By using LocalStack inside a Docker Compose file, you can simulate all essential AWS services locally, allowing fast, offline development and testing.


1. Setting Up Docker Compose

We configure LocalStack to run a mock DynamoDB endpoint in our development Compose file:

version: '3.8'
services:
  localstack:
    image: localstack/localstack:latest
    ports:
      - "4566:4566"
    environment:
      - SERVICES=dynamodb,sqs,sns
      - DEFAULT_REGION=us-east-1
    volumes:
      - "./.localstack:/var/lib/localstack"

2. Overriding Client Endpoints in Python

When running in a local environment, our Python backend detects the local environment variable and routes database queries to the LocalStack endpoint rather than real AWS servers:

import boto3
import os

def get_dynamodb_client():
    endpoint = os.environ.get("AWS_DYNAMODB_ENDPOINT")
    if endpoint:
        # Route to local Docker container (e.g., http://localhost:4566)
        return boto3.client("dynamodb", endpoint_url=endpoint)
    return boto3.client("dynamodb")

This allows tests to run instantly without requiring active AWS accounts or internet connections.