Run sqlcmd and create database table after docker container started from docker-compose?

Hello,

I’m trying to automate a bit of manual setup when starting up my docker containers with docker-compose. I’d like it to create a specific database when it spins up.


services:
  mssql:
    image: "mcr.microsoft.com/mssql/server:latest-ubuntu"
    networks:
      - family
    environment:
      SA_PASSWORD: "123456"
      ACCEPT_EULA: "Y"
    ports:
      - "1433:1433"
  python:
    build:
      context: ./build
      dockerfile: python.dock
    env_file:
      - .env
    networks:
      - family
    volumes:
      - .:/home/code
    depends_on:
      - ubuntu
      - mssql
  ubuntu:
    build:
      context: ./build
      dockerfile: ubuntu.dock
    volumes:
      - ./transfer:/home/
    networks:
      - family
    ports:
      - "60000:22"
networks:
  family:

Currently I have to manually enter the python image and run the command:

sqlcmd -S mssql -U sa -P '123456'

That fires up the sqlcmd prompt where I can then run create database mydatabase and go, then exit to get out of that sqlcmd prompt.

Is there a way to automate this so that it connects and creates the database automatically?

Since microsoft did not add that feature in the image (unlike every single other databases images on the hub), you might be out of luck. If you were using kubernetes, jobs or init-containers might have been a solution. But here you’re out of luck. At least directly.
You may want to customize the mssql image so it create a database (whose name is in the environement) if it does not already exist. A shell script like this as a new entrypoint might do the trick :

#!/bin/bash
isSQLready() {
  :
  # Do whatever is needed to check is mssql is ready or not
}
createDB() {
  while ! isSQLready; do
    sleep 2
  done
  sqlcmd -S mssql -U sa -P "$MSSQL_SA_PASSWORD" <<ENDSQL
create database $MSSQL_DATABASE
go
ENDSQL
}
(createDB; ) &
exec /path/to/initialEntryPoint

You’ll probably want to make sure you dont create an already created database 1st too, but that’s up to you :wink: