Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put seed data into SQL Server docker image?

I have a project using ASP.NET Core and SQL Server. I am trying to put everything in docker containers. For my app I need to have some initial data in the database. I am able to use docker sql server image from microsoft (microsoft/mssql-server-linux), but it is (obviously) empty. Here is my docker-compose.yml:

version: "3"
services:
    web:
        build: .\MyProject
        ports:
            - "80:80"
        depends_on:
            - db
    db:
        image: "microsoft/mssql-server-linux"
        environment:
            SA_PASSWORD: "your_password1!"
            ACCEPT_EULA: "Y"

I have an SQL script file that I need to run on the database to insert initial data. I found an example for mongodb, but I cannot find which tool can I use instead of mongoimport.

like image 847
ironic Avatar asked Oct 24 '17 14:10

ironic


1 Answers

You can achieve this by building a custom image. I'm currently using the following solution. Somewhere in your dockerfile should be:

RUN mkdir -p /opt/scripts
COPY database.sql /opt/scripts

ENV MSSQL_SA_PASSWORD=Passw@rd
ENV ACCEPT_EULA=Y

RUN /opt/mssql/bin/sqlservr --accept-eula & sleep 30  & /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'Passw@rd' -d master -i /opt/scripts/database.sql 

Alternatively you can wait for a certain text to be outputted, useful when working on the dockerfile setup, as it is immediate. It's less robust as it relies on some 'random' text of course:

RUN ( /opt/mssql/bin/sqlservr --accept-eula & ) | grep -q "Service Broker manager has started" \
    && /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'Passw@rd' -i /opt/scripts/database.sql

Don't forget to put a database.sql (with your script) next to the dockerfile, as that is copied into the image.

like image 69
Roet Avatar answered Oct 27 '22 09:10

Roet