58.2 Project 18: Every language in a container with DynamoDB (DynamoDB Local and LocalStack first, then real DynamoDB with an IAM role)
Friends, today we talk to DynamoDB from containers. First DynamoDB Local on your laptop, then LocalStack, then real DynamoDB with an IAM role and no keys in files. Type every command yourself.
मित्रांनो, आज आपण containers मधून DynamoDB शी बोलू. आधी DynamoDB Local, नंतर LocalStack, नंतर IAM role सह real DynamoDB आणि files मध्ये keys नाहीत. प्रत्येक command स्वतः टाइप करा.
दोस्तों, आज हम containers से DynamoDB से बात करेंगे. पहले DynamoDB Local, फिर LocalStack, फिर IAM role के साथ real DynamoDB और files में keys नहीं. हर command खुद टाइप कीजिए.
What you will learn in this lesson
- Why DynamoDB Local comes before real AWS
- How to create a table with Partition and Sort keys
- How Node and Python put and get items
- How IAM roles replace access keys
- How to clean up tables and LocalStack volumes
1. Start from a real problem
Suppose Swiggy or Zomato stores restaurant menus as key-value items that need single-digit millisecond reads.
Relational joins are the wrong shape. DynamoDB fits. But practising only on real AWS burns money and time.
Amazon retail teams and Indian food-delivery backends practise on DynamoDB Local first, then promote the same code with an IAM role.
2. DynamoDB Local with Compose
Step 1: Project folder and Local container
Why: Amazon DynamoDB Local image.
What: A single service on port 8000 with a shared-db volume keeps tables across restarts.
Example 1: Make folder
Type this:
mkdir -p dynamo-langs/{node,python} && cd dynamo-langs && pwd
You will see:
/home/you/dynamo-langs
What it means: Project root ready.
Example 2: Write compose.yaml
Type this:
printf '%s\n' 'name: dynamo-langs' 'services:' ' dynamodb:' ' image: amazon/dynamodb-local:2.5.2' ' command: "-jar DynamoDBLocal.jar -sharedDb -dbPath /data"' ' ports: ["8000:8000"]' ' volumes: [dynamo-data:/data]' 'volumes: {dynamo-data:}' > compose.yaml && wc -l compose.yaml
You will see:
12 compose.yaml
What it means: DynamoDB Local with sharedDb.
Example 3: Start Local
Type this:
docker compose up -d dynamodb && docker compose ps
You will see:
dynamodb ... Up
What it means: Listening on 8000.
Step 2: Create the Menu table
Why: PK restaurantId, SK itemId.
What: Use the AWS CLI with a fake region and endpoint-url pointing at Local.
Example 4: Dummy credentials for Local
Type this:
printf '%s\n' '[default]' 'aws_access_key_id=local' 'aws_secret_access_key=local' > /tmp/local.aws && export AWS_SHARED_CREDENTIALS_FILE=/tmp/local.aws AWS_DEFAULT_REGION=ap-south-1
You will see:
(no output)
What it means: Local accepts any keys.
Example 5: Create table
Type this:
aws dynamodb create-table --endpoint-url http://localhost:8000 --table-name Menu --attribute-definitions AttributeName=restaurantId,AttributeType=S AttributeName=itemId,AttributeType=S --key-schema AttributeName=restaurantId,KeyType=HASH AttributeName=itemId,KeyType=RANGE --billing-mode PAY_PER_REQUEST
You will see:
TableDescription ... TableStatus: ACTIVE
What it means: Menu table ready.
Example 6: List tables
Type this:
aws dynamodb list-tables --endpoint-url http://localhost:8000
You will see:
{"TableNames":["Menu"]}
What it means: Table visible.
3. Put and get items
Step 3: AWS CLI put and get
Why: Prove the table before code.
What: Put one menu item and get it back by both keys.
Example 7: Put item
Type this:
aws dynamodb put-item --endpoint-url http://localhost:8000 --table-name Menu --item '{"restaurantId":{"S":"r1"},"itemId":{"S":"i1"},"name":{"S":"Misal Pav"},"price":{"N":"80"}}'
You will see:
(no output)
What it means: Item stored.
Example 8: Get item
Type this:
aws dynamodb get-item --endpoint-url http://localhost:8000 --table-name Menu --key '{"restaurantId":{"S":"r1"},"itemId":{"S":"i1"}}'
You will see:
Item ... Misal Pav
What it means: Round trip works.
Example 9: Scan count
Type this:
aws dynamodb scan --endpoint-url http://localhost:8000 --table-name Menu --select COUNT
You will see:
{"Count":1}
What it means: One item in the table.
Step 4: Node.js Document Client
Why: @aws-sdk/client-dynamodb style env.
What: Node uses ENDPOINT, TABLE, REGION. Against Local, set ENDPOINT=http://dynamodb:8000.
Example 10: Write node/package.json
Type this:
printf '%s\n' '{' ' "name": "menu-node",' ' "main": "server.js",' ' "dependencies": { "express": "4.19.2", "@aws-sdk/client-dynamodb": "3.670.0", "@aws-sdk/lib-dynamodb": "3.670.0" }' '}' > node/package.json && wc -l node/package.json
You will see:
8 node/package.json
What it means: Express and AWS SDK v3.
Example 11: Write node/server.js
Type this:
printf '%s\n' 'const express = require("express");' 'const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");' 'const { DynamoDBDocumentClient, GetCommand, PutCommand } = require("@aws-sdk/lib-dynamodb");' 'const app = express(); app.use(express.json());' 'const raw = new DynamoDBClient({ region: process.env.AWS_REGION || "ap-south-1", endpoint: process.env.ENDPOINT || undefined });' 'const ddb = DynamoDBDocumentClient.from(raw);' 'const Table = process.env.TABLE || "Menu";' 'app.get("/healthz", (_,res) => res.json({ ok: true, lang: "node" }));' 'app.get("/menu/:rid/:iid", async (req,res) => { const r = await ddb.send(new GetCommand({ TableName: Table, Key: { restaurantId: req.params.rid, itemId: req.params.iid } })); res.json(r.Item || {}); });' 'app.post("/menu", async (req,res) => { await ddb.send(new PutCommand({ TableName: Table, Item: req.body })); res.json({ saved: true }); });' 'app.listen(3000, () => console.log("menu-node on 3000"));' > node/server.js && wc -l node/server.js
You will see:
16 node/server.js
What it means: Get and put against Document Client.
Example 12: Write node/Dockerfile
Type this:
printf '%s\n' 'FROM node:20-alpine' 'WORKDIR /app' 'COPY package.json .' 'RUN npm install --omit=dev' 'COPY server.js .' 'USER node' 'EXPOSE 3000' 'CMD ["node","server.js"]' > node/Dockerfile && grep USER node/Dockerfile
You will see:
USER node
What it means: Non-root Node.
Step 5: Python boto3 client
Why: Same ENDPOINT env.
What: boto3 resource with endpoint_url talks to Local the same way.
Example 13: Write python/main.py
Type this:
printf '%s\n' 'import os, boto3' 'from fastapi import FastAPI' 'app = FastAPI()' 'kw = {"region_name": os.getenv("AWS_REGION","ap-south-1")}' 'if os.getenv("ENDPOINT"): kw["endpoint_url"] = os.environ["ENDPOINT"]' 'table = boto3.resource("dynamodb", **kw).Table(os.getenv("TABLE","Menu"))' '@app.get("/healthz")' 'def health(): return {"ok": True, "lang": "python"}' '@app.get("/menu/{rid}/{iid}")' 'def get_item(rid: str, iid: str): return table.get_item(Key={"restaurantId": rid, "itemId": iid}).get("Item", {})' '@app.post("/menu")' 'def put_item(body: dict): table.put_item(Item=body); return {"saved": True}' > python/main.py && wc -l python/main.py
You will see:
14 python/main.py
What it means: FastAPI plus boto3.
Example 14: Write python/Dockerfile
Type this:
printf '%s\n' 'FROM python:3.12-slim' 'WORKDIR /app' 'RUN pip install --no-cache-dir fastapi uvicorn boto3' 'COPY main.py .' 'USER nobody' 'EXPOSE 8000' 'CMD ["uvicorn","main:app","--host","0.0.0.0","--port","8000"]' > python/Dockerfile && grep USER python/Dockerfile
You will see:
USER nobody
What it means: Non-root Python.
Example 15: Shared env block
Type this:
printf '%s\n' 'ENDPOINT=http://dynamodb:8000' 'TABLE=Menu' 'AWS_REGION=ap-south-1' 'AWS_ACCESS_KEY_ID=local' 'AWS_SECRET_ACCESS_KEY=local'
You will see:
ENDPOINT=http://dynamodb:8000
TABLE=Menu
AWS_REGION=ap-south-1
AWS_ACCESS_KEY_ID=local
AWS_SECRET_ACCESS_KEY=local
What it means: Local keys are fake and fine only for Local.
4. Run both languages and LocalStack
Step 6: Compose apps against Local
Why: Node 3000, Python 8000.
What: Add both services to compose.yaml with the shared env.
Example 16: Append services
Type this:
printf '%s\n' ' node:' ' build: ./node' ' ports: ["3000:3000"]' ' environment:' ' ENDPOINT: http://dynamodb:8000' ' TABLE: Menu' ' AWS_REGION: ap-south-1' ' AWS_ACCESS_KEY_ID: local' ' AWS_SECRET_ACCESS_KEY: local' ' python:' ' build: ./python' ' ports: ["8000:8000"]' ' environment:' ' ENDPOINT: http://dynamodb:8000' ' TABLE: Menu' ' AWS_REGION: ap-south-1' ' AWS_ACCESS_KEY_ID: local' ' AWS_SECRET_ACCESS_KEY: local' >> compose.yaml && docker compose up -d --build node python
You will see:
... Started
What it means: Both APIs up.
Example 17: Get from Node
Type this:
curl -s http://localhost:3000/menu/r1/i1
You will see:
{"restaurantId":"r1","itemId":"i1","name":"Misal Pav","price":"80"}
What it means: Node reads Local.
Example 18: Put from Python
Type this:
curl -s -X POST http://localhost:8000/menu -H 'Content-Type: application/json' -d '{"restaurantId":"r1","itemId":"i2","name":"Vada Pav","price":20}'
You will see:
{"saved":true}
What it means: Python wrote a second item.
Step 7: Optional LocalStack path
Why: Second local endpoint.
What: LocalStack also exposes DynamoDB. Useful when you already run other AWS mocks.
Example 19: LocalStack one-liner idea
Type this:
echo 'services.localstack.image=localstack/localstack and EDGE port 4566'
You will see:
services.localstack.image=localstack/localstack and EDGE port 4566
What it means: Use ENDPOINT=http://localstack:4566 when you switch.
Example 20: Same table API
Type this:
echo 'create-table flags stay identical; only endpoint-url changes'
You will see:
create-table flags stay identical; only endpoint-url changes
What it means: Code does not care which local mock you use.
Example 21: When to skip LocalStack
Type this:
echo 'If you only need DynamoDB, DynamoDB Local is smaller and faster'
You will see:
If you only need DynamoDB, DynamoDB Local is smaller and faster
What it means: Pick one local path for the classroom.
5. Real DynamoDB and cleanup
Step 8: IAM role instead of keys
Why: EC2 or ECS task role.
What: On AWS, drop ENDPOINT and fake keys. Attach a role with dynamodb:PutItem and GetItem on your table ARN.
Example 22: Env for real AWS
Type this:
printf '%s\n' 'TABLE=Menu' 'AWS_REGION=ap-south-1' '# no ENDPOINT, no keys — role provides credentials'
You will see:
TABLE=Menu
AWS_REGION=ap-south-1
# no ENDPOINT, no keys — role provides credentials
What it means: SDK uses the default credential chain.
Example 23: Least privilege idea
Type this:
echo 'Allow GetItem PutItem Query on arn:aws:dynamodb:ap-south-1:ACCOUNT:table/Menu only'
You will see:
Allow GetItem PutItem Query on arn:aws:dynamodb:ap-south-1:ACCOUNT:table/Menu only
What it means: Do not grant * on *.
Example 24: Billing alarm
Type this:
echo 'Create a 5 USD billing alarm before creating real tables'
You will see:
Create a 5 USD billing alarm before creating real tables
What it means: Pay-per-request is cheap but still needs a guardrail.
Step 9: Common mistakes
Why: Missing endpoint and wide IAM.
What: Forgetting ENDPOINT on Local sends traffic to real AWS and fails without keys. Granting dynamodb:* on * is too wide.
Example 25: Local needs ENDPOINT
Type this:
grep ENDPOINT compose.yaml | head -1
You will see:
ENDPOINT: http://dynamodb:8000
What it means: Without this, the SDK targets real AWS.
Example 26: Fake keys only for Local
Type this:
echo 'Never reuse local/local against real AWS'
You will see:
Never reuse local/local against real AWS
What it means: Real AWS needs a role or short-lived keys from SSO.
Example 27: Ignore .env
Type this:
printf '%s\n' '.env' > .gitignore && cat .gitignore
You will see:
.env
What it means: Keep secrets out of Git.
Step 10: Clean up
Why: Volumes and real tables.
What: down -v clears Local data. On AWS, delete the table after the lab.
Example 28: Stop stack
Type this:
docker compose down -v
You will see:
... Removed
What it means: Local data gone.
Example 29: Delete real table reminder
Type this:
echo 'aws dynamodb delete-table --table-name Menu'
You will see:
aws dynamodb delete-table --table-name Menu
What it means: Run only against the real account when you are done.
Example 30: Remove images
Type this:
docker image prune -f | tail -1
You will see:
Total reclaimed space: ...
What it means: Disk returned.
Step 11: Health before demos
Why: Hit /healthz first.
What: APIs can be up while DynamoDB Local is still starting. Retry get-item until it works.
Example 31: Node health
Type this:
curl -s http://localhost:3000/healthz
You will see:
{"ok":true,"lang":"node"}
What it means: API process is up.
Example 32: Python health
Type this:
curl -s http://localhost:8000/healthz
You will see:
{"ok":true,"lang":"python"}
What it means: API process is up.
Example 33: Retry get
Type this:
curl -s http://localhost:3000/menu/r1/i1 | head -c 40
You will see:
{"restaurantId":"r1"
What it means: Data path works.
Step 12: Query by restaurant
Why: PK only query.
What: A query on restaurantId returns all items for that restaurant without a full scan.
Example 34: Query r1
Type this:
aws dynamodb query --endpoint-url http://localhost:8000 --table-name Menu --key-condition-expression 'restaurantId = :r' --expression-attribute-values '{":r":{"S":"r1"}}'
You will see:
Count: 2 ... Misal Pav ... Vada Pav
What it means: Both items for restaurant r1.
Example 35: Why not scan
Type this:
echo 'Scan reads the whole table and costs more as data grows'
You will see:
Scan reads the whole table and costs more as data grows
What it means: Prefer Query with PK.
Example 36: Projection idea
Type this:
echo 'ProjectionExpression name,price returns only those attributes'
You will see:
ProjectionExpression name,price returns only those attributes
What it means: Smaller payloads for mobile clients.
Ravindra Bagale's Tip
Practise on DynamoDB Local, then LocalStack, then real DynamoDB with an IAM role. Never put access keys in Compose files.
आधी DynamoDB Local, नंतर LocalStack, नंतर IAM role सह real DynamoDB. Compose files मध्ये access keys कधीही ठेवू नका.
पहले DynamoDB Local, फिर LocalStack, फिर IAM role के साथ real DynamoDB. Compose files में access keys कभी न रखें.
Check yourself
Q1. Why start with DynamoDB Local?
It is free, offline and matches the API closely enough for classroom work.
Q2. What are PK and SK?
Partition key and sort key that uniquely identify an item.
Q3. Where should AWS keys never go?
Into Compose files, images or Git.
Q4. How do apps on EC2 call real DynamoDB?
With an instance or task IAM role.
Q5. What endpoint does DynamoDB Local use?
http://dynamodb:8000 inside Compose.
Q6. What do you delete after a real-AWS lab?
The table and any unused IAM policies you created.
Friends, you created a table on DynamoDB Local, put and got items from Node and Python, and learned how an IAM role replaces keys for real DynamoDB. Did you understand? Let us try it once more.
मित्रांनो, तुम्ही DynamoDB Local वर table बनवली, Node आणि Python मधून items put/get केली, आणि IAM role keys कसे बदलतो हे शिकलात.
दोस्तों, आपने DynamoDB Local पर table बनाई, Node और Python से items put/get किए, और सीखा कि IAM role keys कैसे बदलता है.
Lab: try at home
- Create the dynamo-langs folder and compose for DynamoDB Local.
- Create the Menu table with PK and SK.
- Put and get an item with the AWS CLI against Local.
- Run Node and Python containers that share the endpoint.
- Write the IAM role plan on paper for real DynamoDB.
- Clean up volumes and local tables.
Recap
- DynamoDB Local first.
- PK and SK identify items.
- Share ENDPOINT and TABLE env vars.
- IAM roles beat access keys.
- LocalStack is a second local path.
- Delete real tables after practice.
Revision card
Interview card