serverless.yml不在本地创建动态表

时间:2019-02-20 00:23:41

标签: docker docker-compose amazon-dynamodb serverless

我有一个同时在docker中运行无服务器和dynamodb的docker设置。在我的serverless.yml中,我定义了创建表的说明,但是当我运行docker compose up时,它并不会创建表(我已经通过运行查询来列出表进行检查。

serverless.yml

...
provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: eu-west-1

plugins:
  - serverless-dynamodb-local
  - serverless-offline

custom:
  dynamodb:
    inMemory: true
    port: 8000
    migrate: true # create tables on start
    onStart: true
  serverless-offline:
    babelOptions:
      presets: ["es2015"]

resources:
  Resources:
    UserTable:
      Type: "AWS::DynamoDB::Table"
      Properties:
        TableName: UserTable
        AttributeDefinitions:
          - AttributeName: userId
            AttributeType: S
          - AttributeName: fullname
            AttributeType: S
        KeySchema:
          - AttributeName: userId
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1

docker-compose.yml

version: "3"

services:
  serverless:
    build: .
    restart: always
    privileged: true
    working_dir: /home/node-app
    environment:
      - NODE_ENV=development
      - DYNAMO_ENDPOINT=http://dynamodb:8000
      - AWS_ACCESS_KEY_ID='dev-key-id'
      - AWS_SECRET_ACCESS_KEY='dev-key'
      - AWS_REGION='eu-west-1'
    links:
      - "dynamodb:dynamodb"
    command: npm run start
  ....
  dynamodb:
    image: amazon/dynamodb-local
    ports:
      - "8000:8000"
    environment:
      - AWS_ACCESS_KEY_ID='dev-key-id'
      - AWS_SECRET_ACCESS_KEY='dev-key'

npm run start仅运行sls offline。一旦我运行了docker compose,一切就可以正常启动,但是没有创建UserTable

enter image description here

1 个答案:

答案 0 :(得分:0)

如果您使用Docker管理DynamoDB服务,则需要指示serverless-dynamodb-local插件为您创建表。

您可以通过运行以下命令来实现:

serverless dynamodb migrate

DynamoDB local的Docker版本的一个常见陷阱是,只有使用用于创建表的相同AWS Access Key ID的客户端才能看到这些表,例如,即使您运行list-tables也不会显示任何表已经成功创建了一个。

$ aws dynamodb list-tables --endpoint "http://localhost:8000"
{
    "TableNames": []
}

最简单的解决方法可能是将-sharedDb选项传递给DynamoDB:

docker run -p 8000:8000 -d amazon/dynamodb-local -jar DynamoDBLocal.jar -sharedDb

(GitHub source)

然后在运行serverless dynamodb migrate之后产生预期的输出:

aws dynamodb list-tables --endpoint "http://localhost:8000"
{
    "TableNames": [
        "SampleDynamoTable-local"
    ]
}