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.

Seeding Deterministic LocalStack Tables on Container Startup

Mount an initialization script into /etc/localstack/init/ready.d/ so LocalStack automatically provisions DynamoDB tables, GSIs, and SQS queues before your Pytest suite starts.


About the Author — Hire Freelance Programmer Aldian Fazrihady

Aldian Fazrihady is a Top-Rated Senior Freelance Programmer, Freelance Full Stack Developer, and AI Application Engineer with 15+ years of production software engineering experience and Google Cloud Professional Cloud Architect & Data Engineer certifications. He specializes in building custom LLM & autonomous AI agents, RAG pipelines, Next.js/React PWAs, Python (Django/FastAPI), Go microservices, and serverless cloud infrastructure on Google Cloud Run and AWS.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD via Polar) | View Live AI Portfolio | Portfolio Directory | Send a Direct Message

Related Engineering Articles

Freelance Programmer Specializations & Category Hubs