在 docker 上启动 SQL Server 后运行 SQL 脚本 [英] Run SQL script after start of SQL Server on docker

查看:42
本文介绍了在 docker 上启动 SQL Server 后运行 SQL 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下代码的 Dockerfile

I have a Dockerfile with below code

FROM microsoft/mssql-server-windows-express
COPY ./create-db.sql .
ENV ACCEPT_EULA=Y
ENV sa_password=##$wo0RD!
CMD sqlcmd -i create-db.sql

并且我可以创建图像,但是当我使用图像运行容器时,我在 SQL Server 上看不到创建的数据库,因为脚本是在 SQL Server 启动之前执行的.

and I can create image but when I run container with the image I don't see created database on the SQL Server because the script is executed before SQL Server was started.

是否可以在使用 SQL Server 启动服务后执行脚本?

Can I do that the script will be execute after start the service with SQL Server?

推荐答案

RUN 用于在图像中构建层.CMD 是在您基于图像启动实例(容器")时运行的命令.

此外,如果您的脚本依赖于这些环境变量,如果它是旧版本的 Docker,它可能会失败,因为这些变量没有按照您希望的方式定义!

Also, if your script depends on those environment variables, if it's an older version of Docker, it might fail because those variables are not defined the way you want them defined!

在旧版本的 docker Dockerfile ENV 命令使用空格而不是="

In older versions of docker the Dockerfile ENV command uses spaces instead of "="

您的 Dockerfile 应该是:

Your Dockerfile should probably be:

FROM microsoft/mssql-server-windows-express
COPY ./create-db.sql .
ENV ACCEPT_EULA Y
ENV sa_password ##$wo0RD!
RUN sqlcmd -i create-db.sql 

这将创建一个包含数据库的图像,其中包含您的密码.

This will create an image containing the database with your password inside it.

(如果 SQL 文件以某种方式使用了环境变量,这将没有意义,因为您最好在复制之前更新 SQL 文件.)如果您希望能够在 docker 构建之间覆盖密码和 docker run 步骤,通过使用 docker run --env sa_password=##$wo0RD!...,您需要将最后一行更改为:

(If the SQL file somehow uses the environment variables, this wouldn't make sense as you might as well update the SQL file before you copy it over.) If you want to be able to override the password between the docker build and docker run steps, by using docker run --env sa_password=##$wo0RD! ..., you will need to change the last line to:

CMD sqlcmd -i create-db.sql && .\start -sa_password $env:sa_password \
-ACCEPT_EULA $env:ACCEPT_EULA -attach_dbs \"$env:attach_dbs\" -Verbose

这是从上游图像继承的CMD行的修改版本.

Which is a modified version of the CMD line that is inherited from the upstream image.

这篇关于在 docker 上启动 SQL Server 后运行 SQL 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆