google-cloud-spannergoogle-cloud-spanner-emulator

Cloud Spanner Emulator - docker initialization


I'm trying to setup a docker container that starts cloud spanner and that initializes it.

Using this official docker image provided by google: gcr.io/cloud-spanner-emulator/emulator

I'm looking to automatically initialize spanner on start.

I tried various things with the docker file, to summarize:

FROM gcr.io/cloud-spanner-emulator/emulator

RUN some gcloud command after to initialize local spanner db

But absence of informations on how this image works makes it hard to find if it's even possible to initialize it everytime the container starts.

I repeat myself, I need this to be run automatically when the container mounts. It's going to build pipelines.

Is there a way to do that with this provided docker image? Or should I create my own dockerfile that installs the emulator via gcloud cli?


Solution

  • Here is a docker file example that allows to start docker emulator and to initialize with some custom gcloud commands

    FROM google/cloud-sdk:slim
    
    RUN apt-get install -y google-cloud-sdk google-cloud-sdk-spanner-emulator
    
    COPY ./start_spanner.bash start_spanner.bash
    COPY ./schema.ddl schema.ddl
    
    CMD ./start_spanner.bash
    

    Here is a sample content of file start_spanner.bash.

    #!/bin/bash
    
    set -m
    
    gcloud beta emulators spanner start --host-port=0.0.0.0:9010 &
    
    # configure gcloud cli to connect to emulator
    gcloud config set auth/disable_credentials true
    gcloud config set project someproject
    gcloud config set api_endpoint_overrides/spanner http://localhost:9020/
    
    # create spanner instance
    gcloud spanner instances create someinstance \
      --config=emulator-config \
      --description="Test Instance" \
      --nodes=1
    
    # create spanner database with the given schema
    gcloud spanner databases create somedb \
     --instance=someinstance \
     --ddl-file=schema.ddl
    
    fg %1
    

    And the file schema.ddl is just your spanner ddl to run to create tables in the emulator as per spanner's documentation.