Docker上的Asp.Net Core + SQL Server-睡眠以启动数据库

Cie*_*eja 5 sql-server entity-framework docker docker-compose asp.net-core

我注意到,当我第一次尝试运行docker-compose up命令时,出现错误:

Starting mssql ...
Starting mssql ... done
Recreating api ...
Recreating api ... done
Attaching to mssql, api
api exited with code 1
Run Code Online (Sandbox Code Playgroud)

因为api试图从数据库获取数据,但是MSSQL尚未启动。

因此,我的问题是有可能以某种方式等待数据库,然后再运行API吗?

这是我的docker-compose和dockerfile

docker-compose:版本:'3.3'

服务:

  api:
    image: api
    container_name: api
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8000:80"
    depends_on:
      - db
  db:
    image: "microsoft/mssql-server-linux"
    container_name: mssql
    environment:
        SA_PASSWORD: "testtest3030!"
        ACCEPT_EULA: "Y"
        MSSQL_PID: "Express"
    ports:
      - "8001:1433"
Run Code Online (Sandbox Code Playgroud)

dockerfile:

# Build Stage
FROM microsoft/aspnetcore-build as build-env
WORKDIR /source
COPY . .
RUN dotnet restore
RUN dotnet publish -o /publish --configuration Release

# Publish Stage
FROM microsoft/aspnetcore
WORKDIR /app
COPY --from=build-env /publish .
ENTRYPOINT ["dotnet", "Api.dll"]
Run Code Online (Sandbox Code Playgroud)

我还在日志中注意到:

2017-11-17 22:12:42.67 Logon       Error: 18456, Severity: 14, State: 38.
2017-11-17 22:12:42.67 Logon       Login failed for user 'sa'. Reason: Failed to open the explicitly specified database 'MyDb'. [CLIENT: 172.26.0.3]
Run Code Online (Sandbox Code Playgroud)

小智 0

您可以使用一个简单的entrypoint.sh脚本:

#!/bin/bash

set -e

run_cmd="dotnet your_app.dll"

sleep 10

exec $run_cmd
Run Code Online (Sandbox Code Playgroud)

并且 docker 文件也会相应改变:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-bionic AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

COPY ["src/entrypoint.sh", ""]
RUN chmod +x entrypoint.sh

# .... here your copy/restore/build/publish

ENTRYPOINT [ "/bin/bash", "entrypoint.sh" ]
Run Code Online (Sandbox Code Playgroud)