问题描述
我有一个使用ASP.NET Core和SQL Server的项目。我正在尝试将所有内容放入docker容器中。对于我的应用程序,我需要在数据库中包含一些初始数据。
我能够使用来自Microsoft(microsoft / mssql-server-linux)的docker sql server镜像,但是(显然)它是空的。这是我的docker-compose.yml:
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"
我有一个需要运行的SQL脚本文件在数据库中插入初始数据。我为mongodb找到了,但是我找不到可以代替mongoimport使用的工具。
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.
推荐答案
您可以通过构建自定义图像来实现。我目前正在使用以下解决方案。 dockerfile中的某个位置应该是:
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
或者,您可以等待输出特定文本,这在处理dockerfile设置时非常有用,因为它是立即生成的。由于它依赖于某些随机文本,因此它的健壮性较低:
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
不要忘记将dockerfile旁边的database.sql(带有脚本)放置在dockerfile旁边,因为它已复制到映像中。
Don't forget to put a database.sql (with your script) next to the dockerfile, as that is copied into the image.
这篇关于如何将种子数据放入SQL Server Docker映像中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!