Docker撰写不启动mongo服务甚至主要服务取决于它

我正在尝试构buildcistream程,使用Docker-Compose和bash脚本构build,testing和发布我的.NET Core应用程序。

我有一个文件夹中的UnitTests,IntegrationTests和XApi项目,并创build了DockerFiledocker-compose.yml如下所示。

IntegrationTests依赖于mongointegration ,所以我添加了linksdepends_on属性来testandpublishdepends_on testandpublish docker-compose.yml服务。

当我尝试docker-compose up testandpublish docker-compose up或者docker-compose up testandpublish ,它不能连接mongo。 (DockerFile – 第10步),mongo服务尚未启动(不明白为什么)

在步骤10中,如果我将RUN更改为CMD ,则可以连接到mongo,docker-compose正常工作。 但这次我无法检测到testing失败或在我的sh脚本中成功,因为现在它不会破坏docker-compose up命令。

我的问题是:为什么docker撰写不启动服务mongointegration ? 如果不可能,我怎么能理解服务testandpublish失败? 谢谢。

结构体:

 XProject -src -Tests -UnitTests -IntegrationTests -Dockerfile -docker-compose.yml -XApi 

我的Dockerfile内容是(我已经添加行号来解释问题在这里):

 1.FROM microsoft/dotnet:1.1.0-sdk-projectjson 2.COPY . /app 3.WORKDIR /app/src/Tests/UnitTests 4.RUN ["dotnet", "restore"] 5.RUN ["dotnet", "build"] 6.RUN ["dotnet", "test"] 7.WORKDIR /app/src/Tests/IntegrationTests 8.RUN ["dotnet", "restore"] 9.RUN ["dotnet", "build"] 10.RUN ["dotnet", "test"] 11.WORKDIR /app/src/XApi 12.RUN ["dotnet", "restore"] 13.RUN ["dotnet", "build"] 14.CMD ["dotnet", "publish", "-c", "Release", "-o", "publish"] 

和我的docker-compose.yml

 version: "3" services: testandpublish: build: . links: - mongointegration depends_on: - mongointegration mongointegration: image: mongo ports: - "27017:27017" 

docker构成中的图像构build阶段和容器运行阶段是两个非常独立的步骤。

build立和运行的差异

构build阶段根据Dockerfile中的步骤创build每个图像层。 每个都在独立的容器中发生。 在生成过程中,除了特定于服务构build的build:节之外,您的服务configuration都不可用。

一旦图像被构build,它就可以作为一个容器与其他的docker-compose服务configuration一起运行。

不要在Dockerfile中运行testing,而是可以创build一个脚本来用作在容器中运行所有testing步骤的CMD

 #!/bin/sh set -uex cd /app/src/Tests/UnitTests dotnet restore dotnet build dotnet test cd /app/src/Tests/IntegrationTests dotnet restore dotnet build dotnet test" cd /app/src/XApi dotnet restore dotnet build dotnet publish -c Release -o publish 

如果microsoft/dotnet:1.1.0-sdk-projectjson映像是基于Windows的,则可能需要将其转换为等效的CMD或PS命令。

容器依赖关系

depends_on不如大多数人认为的那样好。 以简单的forms, depends_on只是在移动到启动依赖容器之前等待容器启动。 等待容器内的过程准备就绪并不够智能。 适当的依赖可以通过健康healthcheckcondition来完成 。

 services: testandpublish: build: . links: - mongointegration depends_on: mongointegration: condition: service_healthy mongointegration: image: mongo ports: - "27017:27017" healthcheck: test: ["CMD", "docker-healthcheck"] interval: 30s timeout: s retries: 3 

使用Docker运行状况检查脚本 ,通过Dockerfile将其复制到容器中之后。

 #!/bin/bash set -eo pipefail host="$(hostname --ip-address || echo '127.0.0.1')" if mongo --quiet "$host/test" --eval 'quit(db.runCommand({ ping: 1 }).ok ? 0 : 1)'; then exit 0 fi exit 1 

RUN步骤在Docker构build映像时执行,并且没有容器可用。 而是在运行时执行CMD步骤,并且Docker Compose已经启动,具体取决于mongointegration容器。