Docker Compose Sql server启动时自动创建数据库和表

问题描述 投票:0回答:1

我使用Sql Server创建了一个asp.net核心网络api。通过运行docker compose文件,我需要创建一个数据库和表。我的解决方法如下

Dockerfile

FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY StarterPackMSSQL.StarterPackMSSQL.csproj StarterPackMSSQL/
RUN dotnet restore StarterPackMSSQL/StarterPackMSSQL.csproj
COPY . .
WORKDIR /src/StarterPackMSSQL
RUN dotnet build StarterPackMSSQL.csproj -c Release -o /app

FROM build AS publish
RUN dotnet publish StarterPackMSSQL.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "StarterPackMSSQL.dll"]

docker-compose.yml

version: '3.5'

networks : 
  localdev:
    name: localdev

services:
 starterpackmssql:
    image: ${DOCKER_REGISTRY-}mssql
    restart: always
    build:
      context: .
      dockerfile:StarterPackMSSQL/Dockerfile
    ports:
      - "5001:80"
    depends_on:
      - db-server
    networks:
      - localdev

  db-server:
    image: microsoft/mssql-server-linux
    container_name: db-server
    environment:
      - ACCEPT_EULA=Y
      - MSSQL_SA_PASSWORD=password123
      - MSSQL_TCP_PORT=1433

    ports:
      - "1400:1433"
    networks:
      - localdev

SQL脚本

CREATE DATABASE [StarterPacksDB]
GO

USE [StarterPacksDB]
GO

/****** Object:  Table [dbo].[Users]    Script Date: 10/18/2019 10:42:39 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[User](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [handle] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

我只需要在运行docker-compose up时自动创建数据库和表

而且它在Mac和Windows上均应工作。

docker docker-compose asp.net-core-webapi
1个回答
0
投票
但是官方图片建议您也可以在entrypoint.sh脚本可以执行诸如创建数据库或登录之类的操作,附加数据库,导入数据或其他设置任务。看这个例子的using an entrypoint.sh script to create a database and schema and bcp in some data
© www.soinside.com 2019 - 2024. All rights reserved.