Asp.Net Core + SQL Server on Docker - sleep for startup DB

Viewed 1026

I have noticed that when I try to run docker-compose up command for the first time I'm getting an error:

Starting mssql ...
Starting mssql ... done
Recreating api ...
Recreating api ... done
Attaching to mssql, api
api exited with code 1

Because api try to get data from DB but the MSSQL has not been started yet.

So, my question is it possible to somehow wait for DB and after that run API?

Here are my docker-compose and dockerfile

docker-compose: version: '3.3'

services:

  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"

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"]

I also noticed in logs:

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]
1 Answers

You could use a simple entrypoint.sh script:

#!/bin/bash

set -e

run_cmd="dotnet your_app.dll"

sleep 10

exec $run_cmd

And docker file will change accordingly:

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" ]
Related