diff --git a/.gitignore b/.gitignore index 191b3b9..1396d0b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ !.github !.github/**/* !.gitignore -!*.md +!LICENSE.md +!README.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 0952d22..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,83 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our community include: - -- Demonstrating empathy and kindness toward other people -- Being respectful of differing opinions, viewpoints, and experiences -- Giving and gracefully accepting constructive feedback -- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -- Focusing on what is best not just for us as individuals, but for the overall community - -Examples of unacceptable behavior include: - -- The use of sexualized language or imagery, and sexual attention or advances of any kind -- Trolling, insulting or derogatory comments, and personal or political attacks -- Public or private harassment -- Publishing others' private information, such as a physical or email address, without their explicit permission -- Other conduct which could reasonably be considered inappropriate in a professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of actions. - -**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. - -For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. - -[homepage]: https://www.contributor-covenant.org -[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity -[FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 9672e0c..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,43 +0,0 @@ -# Contributing - -We welcome contributions to this project! This repository is primarily a **tutorial and educational resource**, so we are focused on changes that enhance clarity, correctness, and pedagogical value. By participating, you agree to abide by our [code of conduct](./CODE_OF_CONDUCT.md). - ---- - -## Ways to contribute - -### 1. Reporting issues - -- **Found a bug?** If the instructions or code examples don't work, please open a new **Issue**. Be sure to include your operating system, Docker version, and the exact steps to reproduce the error. -- **Suggesting Enhancements?** If you have an idea to make the tutorial clearer or suggest a common, robust alternative approach (e.g., a different base image), feel free to open an Issue to discuss it first. - -### 2. Submitting pull requests (PRs) - -We are looking for PRs that: - -- **Fix typos or incorrect commands** in the `README.md` or configuration files. -- **Improve the explanation or clarity** of the steps. -- **Correct any non-functional code** in `src/index.ts` or configuration files. - -## Pull request guidelines - -1. **Fork** the repository to your own GitHub account. -2. **Clone** your fork locally and navigate into the directory: - ```bash - git clone [https://github.com/YOUR_USERNAME/workshop-template.git](https://github.com/YOUR_USERNAME/workshop-template.git) - cd workshop-template - ``` -3. **Create a new, descriptive branch** for your changes (e.g., `fix/typo-in-readme`). -4. **Make your changes**, ensuring you run `docker compose up` to verify that the project still works after your changes. -5. **Write clear and concise commit messages.** Each commit should address a single logical change. -6. **Push your branch** and open a **Pull Request** against the `main` branch of this repository. - -Please clearly describe what you changed and why in the PR description. - ---- - -## Code of conduct - -Please review and adhere to our [Code of Conduct](./CODE_OF_CONDUCT.md) in all your interactions with the project and its community. - -Thank you for helping us make this a better resource! diff --git a/README.md b/README.md index 7fc4b80..1424365 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,533 @@ -# 📚 Daemon Labs workshop documentation hub +# Learn to build and develop AWS Lambda functions locally with Docker -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md) +This guide walks you through setting up a robust local Serverless development environment using **Docker**, **AWS Lambda**, **TypeScript**, and **LocalStack**. +It focuses on emulating the cloud runtime entirely offline, optimising production images with multi-stage builds, and mocking external services like S3 to create a complete, cost-free development workflow. + +--- ## 🛑 Prerequisites +### General/global prerequisites + Before beginning this workshop, please ensure your environment is correctly set up by following the instructions in our prerequisites documentation: ➡️ **[Prerequisites guide](https://github.com/daemon-labs-resources/prerequisites)** +### Load Docker images + +> [!CAUTION] +> This only works when attending a workshop in person. +> Due to having a number of people trying to retrieve Docker images at the same time, this allows for a more efficient way. +> +> If you are **NOT** in an in-person workshop, continue to the [workshop](#1-the-foundation), Docker images will be pulled as needed. + +Once the facilitator has given you an IP address, open `http://:8000` in your browser. + +When you see the file listing, download the `workshop-images.tar` file. + +> [!WARNING] +> Your browser may block the download initially, when prompted, allow it to download. + +Run the following command: + +```shell +docker load -i ~/Downloads/workshop-images.tar +``` + +### Validate Docker images + +Run the following command: + +```shell +docker images +``` + +> [!NOTE] +> You should now see four images listed. + +--- + +## 1. The foundation + +**Goal:** Get a working container environment running. + +### Create project folder + +Create a new folder for your project: + +```shell +mkdir -p ~/Documents/daemon-labs/docker-aws-lambda +``` + +> [!NOTE] +> You can either create this via a terminal window or your file explorer. + +### Open the new folder in your code editor + +> [!TIP] +> If you are using VSCode, we can now do everything from within the code editor. +> You can open the terminal pane via Terminal -> New Terminal. + +### Create the code subdirectory + +We keep our application code separate from infrastructure config. + +```shell +mkdir ./nodejs +``` + +### Create the `Dockerfile` + +Create the file at `nodejs/Dockerfile` (inside the subdirectory). + +```Dockerfile +FROM public.ecr.aws/lambda/nodejs:24 +``` + +### Create `docker-compose.yaml` + +Create this file in the **root** of your project. + +```yaml +services: + lambda: + build: ./nodejs +``` + +### Initialise the container + +Run this command to start an interactive shell: + +```shell +docker compose run -it --rm --entrypoint /bin/sh -v ./nodejs:/var/task lambda +``` + +### Image check + +Run the following command: + +```shell +node --version +``` + +--- + +## 2. The application + +**Goal:** Initialise a TypeScript Node.js project. + +### Initialise the project + +Inside the container shell: + +```shell +npm init -y +``` + +### Install dependencies + +```shell +npm add --save-dev @types/node@24 @types/aws-lambda @tsconfig/recommended typescript +``` + +### Exit the container + +```shell +exit +``` + +### Configure TypeScript + +Create `nodejs/tsconfig.json` locally: + +```json +{ + "extends": "@tsconfig/recommended/tsconfig.json", + "compilerOptions": { + "outDir": "./build" + } +} +``` + +### Create the handler + +Create `nodejs/src/index.ts`: + +```typescript +import { Handler } from "aws-lambda"; + +export const handler: Handler = async (event, context) => { + console.log("Hello world!"); + console.log({ event, context }); + + return { + statusCode: 200, + body: "Hello World!", + }; +}; +``` + +### Add build script + +Update `nodejs/package.json` scripts: + +```json +"build": "tsc" +``` + +--- + +## 3. The runtime + +**Goal:** Make the container act like a real Lambda server. + +### Add `.dockerignore` + +Create `nodejs/.dockerignore` (inside the subdirectory). +This is critical because our build context is now that specific folder. + +```plaintext +build +node_modules +``` + +### Update `Dockerfile` + +Update `nodejs/Dockerfile`: + +```Dockerfile +FROM public.ecr.aws/lambda/nodejs:24 + +COPY ./package*.json ${LAMBDA_TASK_ROOT} + +RUN npm ci + +COPY ./ ${LAMBDA_TASK_ROOT} + +RUN npm run build + +CMD [ "build/index.handler" ] +``` + +### Update Lambda healthcheck + +Update `docker-compose.yaml`: + +```yaml +lambda: + build: ./nodejs + healthcheck: + test: + - CMD + - curl + - -I + - http://localhost:8080 +``` + +### Add cURL service + +Update `docker-compose.yaml` (in the root) to include a service that triggers our Lambda. + +```yaml +services: + curl: + image: curlimages/curl + depends_on: + lambda: + condition: service_healthy + command: + - -s + - -d {} + - http://lambda:8080/2015-03-31/functions/function/invocations + lambda: + build: ./nodejs +``` + +### Run the stack + +```shell +docker compose up --build --abort-on-container-exit +``` + +--- + +## 4: Developer experience + +**Goal:** Simulate real-world events and environments. + +### Add environment variables + +Update `docker-compose.yaml`: + +```yaml +services: + # ... existing config + lambda: + # ... existing config + environment: + AWS_LAMBDA_FUNCTION_MEMORY_SIZE: 128 + AWS_LAMBDA_FUNCTION_TIMEOUT: 3 + AWS_LAMBDA_LOG_FORMAT: JSON +``` + +### Create the events subdirectory + +Create the events subdirectory in the root (keep events outside the code folder): + +```shell +mkdir ./events +``` + +### Create a custom event file + +Create `events/custom.json`: + +```json +{ + "user": "Alice", + "action": "login" +} +``` + +### Create API Gateway event file + +Create `events/api-gateway.json`: + +```json +{ + "resource": "/", + "path": "/", + "httpMethod": "POST", + "body": "{\"user\": \"Alice\"}", + "isBase64Encoded": false +} +``` + +### Inject the event + +Update `docker-compose.yaml`: + +```yaml +services: + curl: + # ... existing config + command: + - -s + - -d + - ${LAMBDA_INPUT:-{}} + - http://lambda:8080/2015-03-31/functions/function/invocations +volumes: + - ./events:/events:ro + # ... existing config +``` + +### Test with data + +```shell +docker compose up --build --abort-on-container-exit +``` + +```shell +LAMBDA_INPUT=@/events/custom.json docker compose up --build --abort-on-container-exit +``` + +```shell +LAMBDA_INPUT=@/events/api-gateway.json docker compose up --build --abort-on-container-exit +``` + --- -## 📚 Workshop and full documentation +## 5. Optimisation + +**Goal:** Prepare for production with multi-stage builds. + +### Multi-stage build + +Replace `nodejs/Dockerfile` with this optimised version: + +```Dockerfile +FROM public.ecr.aws/lambda/nodejs:24 AS base + +FROM base AS builder + +COPY ./package*.json ${LAMBDA_TASK_ROOT} + +RUN npm ci + +COPY ./ ${LAMBDA_TASK_ROOT} + +RUN npm run build + +FROM base + +COPY --from=builder ${LAMBDA_TASK_ROOT}/package*.json ${LAMBDA_TASK_ROOT} + +RUN npm ci --only=production + +COPY --from=builder ${LAMBDA_TASK_ROOT}/build ${LAMBDA_TASK_ROOT}/build + +CMD [ "build/index.handler" ] +``` + +### Test the optimised build + +Run the following command to ensure everything still works: + +```shell +docker compose up --build --abort-on-container-exit +``` + +--- + +## 6: Advanced integration + +**Goal:** Connect to LocalStack. + +### Add LocalStack Service to `docker-compose.yaml` + +```yaml +localstack: + image: localstack/localstack + healthcheck: + test: + - CMD + - curl + - -f + - http://localhost:4566/_localstack/health + interval: 1s + timeout: 1s + retries: 30 +``` + +### Update Lambda config + +Update `docker-compose.yaml`: + +```yaml +depends_on: + localstack: + condition: service_healthy +environment: + AWS_LAMBDA_FUNCTION_MEMORY_SIZE: 128 + AWS_LAMBDA_FUNCTION_TIMEOUT: 3 + AWS_LAMBDA_LOG_FORMAT: JSON + AWS_ENDPOINT_URL: http://localstack:4566 + AWS_SECRET_ACCESS_KEY: test + AWS_ACCESS_KEY_ID: test + AWS_REGION: us-east-1 +``` + +### Update code + +Run this command to start an interactive shell: + +```shell +docker compose run -it --rm --no-deps --entrypoint /bin/sh -v ./nodejs:/var/task lambda +``` + +Install the SDK: + +```shell +npm install @aws-sdk/client-s3 +``` + +Exit the container + +```shell +exit +``` + +Next, update `nodejs/src/index.ts` with the S3 client logic: + +```typescript +import { Handler } from "aws-lambda"; +import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3"; + +const client = new S3Client({ + endpoint: process.env.AWS_ENDPOINT_URL, // Points to LocalStack + forcePathStyle: true, // Required for local mocking + region: process.env.AWS_REGION, +}); + +export const handler: Handler = async (event, context) => { + try { + const command = new ListBucketsCommand({}); + const response = await client.send(command); + + console.log("S3 Buckets:", response.Buckets); + + return { + statusCode: 200, + body: JSON.stringify(response.Buckets || []), + }; + } catch (error) { + console.error(error); + return { + statusCode: 500, + body: "Error connecting to S3", + }; + } +}; +``` + +### Final run + +Run the following command: + +```shell +docker compose up --build --abort-on-container-exit +``` + +--- + +## 7. Bonus: Swapping runtimes + +**Goal:** Demonstrate the versatility of Docker by swapping to Python. + +One of the biggest advantages of developing Lambdas with Docker is that the infrastructure pattern remains exactly the same, regardless of the language you use. + +### Create a Python `Dockerfile` + +Create `python/Dockerfile` with the following content: + +```Dockerfile +FROM public.ecr.aws/lambda/python:3.14 + +COPY ./ ${LAMBDA_TASK_ROOT} + +CMD [ "app.handler" ] +``` + +### Create the Python handler + +Create the handler file at `python/app.py`: + +```python +def handler(event, context): + return "Hello World!" +``` + +### Update `docker-compose.yaml` + +Update the `lambda` service in `docker-compose.yaml` to point to the Python folder: + +```yaml +services: + lambda: + build: ./python +``` + +### Run it -The detailed, step-by-step instructions and narrative for the project are contained in the main workshop document: +```shell +docker compose up --build --abort-on-container-exit +``` -➡️ **[View the workshop guide](./WORKSHOP.md)** +> [!NOTE] +> You will see the build process switch to pulling the Python base image, but the curl command and event injection work exactly the same way. --- -## Contributing +## 🎉 Congratulations -Please see our [CONTRIBUTING.md](./CONTRIBUTING.md) for more details on submitting changes or improvements to this documentation. +You have built a clean, modular, serverless development environment. diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index 6166f0b..0000000 --- a/SECURITY.md +++ /dev/null @@ -1,27 +0,0 @@ -# Security Policy - -## Reporting a vulnerability - -We take the security of this project seriously. While this repository is primarily an educational resource and is **not intended for production deployment**, we still encourage users to report any security vulnerabilities they discover. - -**Please DO NOT report security issues via public GitHub Issues or Pull Requests.** - -Instead, please report it privately by using GitHub's **"Report a vulnerability"** feature. -You can find this option under the **Security** tab of this repository. - -### Preferred information - -To help us address the issue quickly, please include the following in your report: - -- A brief description of the vulnerability. -- The steps required to reproduce the issue. -- Your environment details (e.g., Docker version, operating system). -- Any suggested mitigations or fixes (if known). - -We will acknowledge your report within 48 hours and provide a detailed response to the reported vulnerability within 7 days. - -## Scope - -The scope of this policy covers the code and configuration files within the `daemon-labs-resources/workshop-template` repository. - -Thank you for helping to keep this project secure. diff --git a/WORKSHOP.md b/WORKSHOP.md deleted file mode 100644 index a943ebf..0000000 --- a/WORKSHOP.md +++ /dev/null @@ -1,29 +0,0 @@ -# Workshop title - -Workshop description. - ---- - -## 1. Section one - -1. **Step one** - Instructions. - - ```text - Any command that needs copying - ``` - - > Any notes. - ---- - -## 2. Section two - -1. **Step one** - Instructions. - - ```text - Any command that needs copying - ``` - - > Any notes.