dockerでDynamoDBのローカル環境を作る

開発メモ

version: '3'
services:
  dynamodblocal:
    container_name: social_app_dynamo_local
    image: amazon/dynamodb-local
    ports:
      - 8000:8000
    command: -jar DynamoDBLocal.jar -sharedDb -dbPath /home/dynamodblocal/data/ # ボリュームの永続化
    volumes:
      - ../dynamodb/data:/home/dynamodblocal/data
    expose:
      - "8000"
  dynamodbadmin:
    container_name: social_app_dynamo_admin
    image: instructure/dynamo-local-admin
    ports:
      - 8001:8001
    depends_on:
      - dynamodblocal
    links:
      - "dynamodblocal:dynamodb"
    environment:
      DYNAMO_ENDPOINT: http://dynamodblocal:8000/

localhost:8000にDBを置く
localhost:8001に管理画面を立てる

この2行でデータの永続化を行なっている

command: -jar DynamoDBLocal.jar -sharedDb -dbPath /home/dynamodblocal/data/
volumes:
  - ../dynamodb/data:/home/dynamodblocal/data

Goで接続関数を書いてみる

package main

import (
    "fmt"
    "time"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
    "github.com/guregu/dynamo"
)

// Post .
type Post struct {
    ID        string                     `dynamo:"ID,hash"`
    Text      string                     `dynamo:"Text"`
    CreatedAt dynamodbattribute.UnixTime `dynamo:"CreatedAt"`
    UpdatedAt dynamodbattribute.UnixTime `dynamo:"UpdatedAt"`
}

func openConnection() *dynamo.DB {
    // デフォルトでは東京リージョンを指定
    sess, err := session.NewSession(&aws.Config{
        Region:      aws.String("ap-northeast-1"),
        Endpoint:    aws.String("http://dynamodb:8000/"),
        Credentials: credentials.NewStaticCredentials("dummy", "dummy", "dummy"),
    })
    if err != nil {
        panic(err)
    }

    db := dynamo.New(sess)
    return db
}

func main() {
    db := openConnection()
    err := db.CreateTable("posts", model.Post{}).Run()
    if err != nil {
        panic(err)
    }
    table := db.Table("posts")
    err = table.Put(&model.Post{ID: "1", Text: "test", CreatedAt: dynamodbattribute.UnixTime(time.Now()), UpdatedAt: dynamodbattribute.UnixTime(time.Now())}).Run()
        if err != nil {
            return err
        }

    readResult := make([]Post, 0, 10)
    err = p.DynamoDB.Table("posts").Get("ID", "1").All(&readResult)
    if err != nil {
        fmt.Printf("Failed to get item[%v]\n", err)
    }
    fmt.Printf(readResult)
}

関連記事