CockroachDB Docker Compose Script with SQL commands
Asked Answered
F

1

7

I would like to accomplish 2 things:

1) Start a CockroachDB cluster with docker compose (works)

2) Execute SQL commands on the cluster (I want to create a Database)

My Docker File Looks like this:

version: '3'

services: 
roach-ui: 
 image: cockroachdb/cockroach
 command: start --insecure
 expose:
  - "8080"
  - "26257"
 ports:
  - "26257:26257"
  - "8080:8080"
 networks:
  - roachnet
db-1: 
 image: cockroachdb/cockroach
 command: start --insecure --join=roach-ui
 networks:
  - roachnet
 volumes: 
  - ./data/db-1:/cockroach/cockroach-data

networks:
 roachnet:

When I run docker-compose up, everything works as expected. While using google, I found that the solution is to run a bash script, I created the following setup.sh:

sql --insecure --execute="CREATE TABLE testDB"

I tried to run the script via command: bash -c "setup.sh", but Docker says that it can not run the command "bash". Any Suggestions ? Thanks :)

EDIT:

I am running docker-compose up, the error I am getting:

roach-ui_1  | Failed running "bash"
heimdall_roach-ui_1 exited with code 1
Fransiscafransisco answered 25/8, 2017 at 14:55 Comment(1)
Would you mind copying and pasting the specific Docker command you're running and the error message you're getting into the question?Tops
S
9

So what you need is an extra init service to initialize the DB. This service will run a bash script to execute commands that will init the DB

setup_db.sh

#!/bin/bash
echo Wait for servers to be up
sleep 10

HOSTPARAMS="--host db-1 --insecure"
SQL="/cockroach/cockroach.sh sql $HOSTPARAMS"

$SQL -e "CREATE DATABASE tarun;"
$SQL -d tarun -e "CREATE TABLE articles(name VARCHAR);"

And then you add this file to execute in the docker-compose.yml

docker-compose.yaml

version: '3'

services:
  roach-ui:
    image: cockroachdb/cockroach
    command: start --insecure
    expose:
     - "8080"
     - "26257"
    ports:
     - "26257:26257"
     - "8080:8080"
    networks:
     - roachnet
  db-1:
    image: cockroachdb/cockroach
    command: start --insecure --join=roach-ui
    networks:
     - roachnet
    volumes:
     - ./data/db-1:/cockroach/cockroach-data
  db-init:
   image: cockroachdb/cockroach
   networks:
    - roachnet
   volumes:
     - ./setup_db.sh:/setup_db.sh
   entrypoint: "/bin/bash"
   command: /setup_db.sh
networks:
  roachnet:
Schaab answered 25/8, 2017 at 20:49 Comment(3)
Thanks so much for the great answer! One divergence that I made was to use depends_on (with db-1 as the value) in the db-init service to make sure it runs after the DB has started, rather than using sleep in the script.Akron
Ideal way is to use a combination of depends_on and github.com/vishnubob/wait-for-itSchaab
You're right—I actually had to reintroduce your sleep 10 line to ensure a successful connection.Akron

© 2022 - 2024 — McMap. All rights reserved.