Ikkyu's Tech Blog

技術系に関するブログです。

DynamoDB Localの使用方法(Docker, Node.js)

Amazon DynamoDBを使用した開発を行う際に、cliやコンソールからAWS上にテーブル作って開発・テストをしてもいいのですが、コスト💸がかかってしまいます。

そこで、DynamoDB Localを使用することで、コストをかけず開発・テストができます。

想定する読者

  • これからDynamoDB Localを使用してみたい人🙋‍♂️

間違いなど不備な点がありましたらコメントしてもらえると助かります。 🙇🏻‍♂️ よろしくお願いします。

前提条件

動作環境

DynamoDB LocalをDockerで起動

amazon/dynamodb-localに載っているコマンドを実行します。

$ docker run -p 8000:8000 amazon/dynamodb-local
Unable to find image 'amazon/dynamodb-local:latest' locally
latest: Pulling from amazon/dynamodb-local
638b75f800bf: Pull complete
106d4bcae1bb: Pull complete
4fda29486f95: Pull complete
Digest: sha256:705acedfeeed8d98781475cecacdfac574969642db4ad0856a49907a44d63c70
Status: Downloaded newer image for amazon/dynamodb-local:latest
Initializing DynamoDB Local with the following configuration:
Port:   8000
InMemory:   true
DbPath: null
SharedDb:   false
shouldDelayTransientStatuses:   false
CorsParams: *

コンテナイメージをPullしてきて、DynamoDBが起動しました。

そしたら別のターミナルを起動し、aws-cliを使用して検証してみます。

aws dynamodb list-tables --endpoint-url http://localhost:8000

結果

{
    "TableNames": []
}

これで起動は終わりです。簡単🤗

Node.jsからテーブルを作成

Node.jsでテーブルを作成します。

const AWS = require("aws-sdk");

async function createTable() {
    const dynamo = new AWS.DynamoDB({
        endpoint: 'http://localhost:8000',
        region: "ap-northeast-1", // 必須 ... 名前は任意の文字列で大丈夫でした。
    });

    const createTableInput = {
        AttributeDefinitions: [
          {
            AttributeName: "Id",
            AttributeType: "S",
          },
        ],
        KeySchema: [
          {
            AttributeName: "Id",
            KeyType: "HASH",
          }
        ],
        ProvisionedThroughput: {
          ReadCapacityUnits: 5,
          WriteCapacityUnits: 5
         },
         TableName: "Test",
    };

    try {
        // テーブルを作成
        const response = await dynamo.createTable(createTableInput).promise();
        console.log(response);
    } catch (e) {
        console.error("テーブル作成失敗", e);
    }
}

createTable(); // 実行

結果

$ node createTable.js
{ TableDescription:
   { AttributeDefinitions: [ [Object] ],
     TableName: 'Test',
     KeySchema: [ [Object] ],
     TableStatus: 'ACTIVE',
     CreationDateTime: 2019-01-20T07:39:58.034Z,
     ProvisionedThroughput:
      { LastIncreaseDateTime: 1970-01-01T00:00:00.000Z,
        LastDecreaseDateTime: 1970-01-01T00:00:00.000Z,
        NumberOfDecreasesToday: 0,
        ReadCapacityUnits: 5,
        WriteCapacityUnits: 5 },
     TableSizeBytes: 0,
     ItemCount: 0,
     TableArn: 'arn:aws:dynamodb:ddblocal:000000000000:table/Test' } }

できました👍

aws-cliでも確認してみます。

$ aws dynamodb describe-table --table-name Test --endpoint-url http://localhost:8000 --region=ap-northeast-1
{
    "Table": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Id",
                "AttributeType": "S"
            }
        ],
        "TableName": "Test",
        "KeySchema": [
            {
                "AttributeName": "Id",
                "KeyType": "HASH"
            }
        ],
        "TableStatus": "ACTIVE",
        "CreationDateTime": 1547969998.034,
        "ProvisionedThroughput": {
            "LastIncreaseDateTime": 0.0,
            "LastDecreaseDateTime": 0.0,
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/Test"
    }
}

aws-cliを使用した確認をする場合の注意点は、--region=ap-northeast-1を指定しないと

$ aws dynamodb describe-table --table-name Test --endpoint-url http://localhost:8000

An error occurred (ResourceNotFoundException) when calling the DescribeTable operation: Cannot do operations on a non-existent table

となる場合がありますので、ご注意ください。aws-cliで使用するデフォルト設定のregionが適用されるからですね。。

DynamoDBを停止

知っている方の方が多いと思いますが、停止させると、データが消えてしまうので注意してください⚠️

NAMES or CONTAINER IDを確認します

$ docker ps -a
CONTAINER ID        IMAGE                                                     COMMAND                  CREATED             STATUS                      PORTS                    NAMES
87e8adf12e82        amazon/dynamodb-local                                     "java -jar DynamoDBL…"   3 hours ago         Up About a minute           0.0.0.0:8000->8000/tcp   flamboyant_margulis

停止させます

$ docker stop flamboyant_margulis

or

$ docker stop 87e8adf12e82

次に起動する時は、

$ docker start flamboyant_margulis

or

$ docker stop 87e8adf12e82

で起動できます💪

以上です。DynamoDB Localの使用方法を紹介しました。 コスト気にせず開発できるのでいいですね!

参考サイト