Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CockroachDB Docker Compose Script with SQL commands

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
like image 925
jona jürgen Avatar asked Aug 25 '17 14:08

jona jürgen


1 Answers

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:
like image 110
Tarun Lalwani Avatar answered Sep 22 '22 04:09

Tarun Lalwani