---
# System prepended metadata

title: AWS SAM Lambda Dockerization
tags: [chatgpt]

---

# AWS SAM Lambda Dockerization

[TOC]

###### tags: `chatgpt`

---

## 打造一個以 aws-serverless-springboot2-archetype 建構的 AWS SAM 專案，其 Lambda function 需容器化，本地測試時能使用包含 PostgreSQL 並將環境變數從本地檔案讀取的 docker-compose.yml，另請給我 template.yml、Dockerfile、docker-compose.yml 的內容

以下是您要求的 AWS SAM 專案所需的檔案內容：

### template.yml

```yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  YourFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: target/my-function-1.0.0.jar
      Handler: com.example.LambdaHandler
      Runtime: java11
      MemorySize: 512
      Timeout: 30
      Environment:
        Variables:
          POSTGRES_DB: !Ref PostgresDB
          POSTGRES_HOST: !Ref PostgresHost
          POSTGRES_PORT: !Ref PostgresPort
          POSTGRES_USER: !Ref PostgresUser
          POSTGRES_PASSWORD: !Ref PostgresPassword
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /hello
            Method: get

  PostgresDB:
    Type: AWS::SSM::Parameter
    Properties:
      Name: /postgres/dbname
      Type: String
      Value: my-database
  PostgresHost:
    Type: AWS::SSM::Parameter
    Properties:
      Name: /postgres/host
      Type: String
      Value: localhost
  PostgresPort:
    Type: AWS::SSM::Parameter
    Properties:
      Name: /postgres/port
      Type: String
      Value: 5432
  PostgresUser:
    Type: AWS::SSM::Parameter
    Properties:
      Name: /postgres/user
      Type: String
      Value: my-user
  PostgresPassword:
    Type: AWS::SSM::Parameter
    Properties:
      Name: /postgres/password
      Type: String
      Value: my-password
```

### Dockerfile

```dockerfile
FROM public.ecr.aws/lambda/java:11

COPY target/my-function-1.0.0.jar ${LAMBDA_TASK_ROOT}

CMD ["com.example.LambdaHandler::handleRequest"]
```

### docker-compose.yml

```yaml
version: '3.8'

services:
  postgres:
    image: postgres
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql

  my-function:
    build: .
    environment:
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_HOST: postgres
      POSTGRES_PORT: 5432
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
```

您可以根據您的需求，自行調整以上檔案內容，尤其是環境變數的值與其他參數。
