Docker 化 Windows 服务

che*_*aou 14 containers windows-services docker docker-for-windows

我是 Docker 新手,我有一个包含一组 Windows 服务(.NET)的应用程序。我想将它运行到 Docker 容器中。我应该怎么办 ?

QA *_*ive 14

我已使用以下 Dockerfile 成功将 Windows 服务放入 Docker 容器中。替换MyWindowsServiceName为您自己的 Windows 服务的名称。

# escape=\

FROM mcr.microsoft.com/dotnet/framework/aspnet:4.7.2-windowsservercore-1709

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

COPY ["MyWindowsServiceName/bin/Release/", "/Service/"]

WORKDIR "C:/Service/"

RUN "C:/Service/InstallUtil.exe" /LogToConsole=true /ShowCallStack MyWindowsServiceName.exe; \
    Set-Service -Name "\"MyWindowsServiceName\"" -StartupType Automatic; \
    Set-ItemProperty "\"Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyWindowsServiceName\"" -Name AllowRemoteConnection -Value 1

ENTRYPOINT ["powershell"]
CMD Start-Service \""MyWindowsServiceName\""; \
    Get-EventLog -LogName System -After (Get-Date).AddHours(-1) | Format-List ;\
    $idx = (get-eventlog -LogName System -Newest 1).Index; \
    while ($true) \
    {; \
    start-sleep -Seconds 1; \
    $idx2  = (Get-EventLog -LogName System -newest 1).index; \
    get-eventlog -logname system -newest ($idx2 - $idx) |  sort index | Format-List; \
    $idx = $idx2; \
    }
Run Code Online (Sandbox Code Playgroud)

注意 1:我的 Windows 服务记录到 Windows 事件系统。因此,该文件末尾包含一些不错的代码,用于根据 Docker 约定将 EventLog 信息打印到控制台。您可能需要也可能不需要此部件来提供您自己的服务。如果没有,则仅使用第一行减去“\”。

注意 2:Windows 服务的名称可能与其可执行文件名称不同。也就是说,“MyWindowsServiceName.exe”的服务名称可能是“My Windows Service Name”或“Fred”,您需要知道这两个名称。


Par*_*iva 0

一般来说,您应该尽可能选择一个已经安装了必要库的基础镜像,而不是选择一个非常基础的镜像(例如普通的 Linux 或 Windows)并在其上安装。

根据您的情况,选择安装了 .NET 的 docker 映像。以该图像为例理想的流程如下。

  1. 选择您要使用的 Docker 镜像
  2. 在项目的根位置包含一个 Dockerfile
  3. 在 Dockerfile 中包含命令以将代码或可执行文件复制到映像上
  4. 指定启动命令
  5. 构建镜像docker build -t YourRepoName .在 Dockerfile 的位置运行它
  6. 测试一下docker run YourImage

Dockerfile这是我为 Springboot 编写的 dockerfile 之一。您可以参考一下。请注意,我仅将此处的 jar 文件复制到我的容器中,而不是源代码,因为在构建 docker 容器时,jar 文件是可用的。您可以选择在 Dockerfile 中包含用于复制源代码和创建可执行文件的命令。