如何建立含有 .NET Core SDK 的 Docker Image ?
雖然 Microsoft 官方提供 .NET Core 的 Docker image,但實務上建置環境時,可能先使用其他 server 的 image,然後再加裝 .NET Core SDK 環境,如此就需要自行建立 Dockerfile,並建立自己的 image。
Version
macOS High Sierra 10.13.3
Docker for Mac 17.12.0-ce-mac55 (23011)
Ubuntu 16.04.3 LTS
.NET Core SDK 2.1.4
Dockerfile
1 | FROM ubuntu |
第 1 行
1 | FROM ubuntu |
以 ubuntu 這個 image 為基底建立 image。
Q : 為什麼不用
ubuntu:lts呢 ?預設
ubuntu即ubuntu:latest,而ubuntu:latest指的就是 latest lts,所以已經是 LTS 版本
第 3 行
1 | # Switch to root to install .NET Core SDK |
因為即將使用 apt-get 安裝 package,所以直接切換到 root 帳號執行以下動作。
第 6 行
1 | # Show distro information! |
顯示目前 image 的版本資訊。
此段並非安裝 .NET Core SDK 所必須,但因為 Linux 的 ditribution 眾多,每個
Dockerfile的寫法也會有所差異,因此這行可以幫助Dockerfile撰寫
第 9 行
1 | # Based on instructiions at https://docs.microsoft.com/en-us/dotnet/core/linux-prerequisites?tabs=netcore2x |
根據官網的 Prerequisites for .NET Core on Linux,若要在 Linux 安裝 .NET Core,在 Ubuntu 還必須安裝以下額外 package :
- libunwind8
- liblttng-ust0
- libcurl3
- libssl1.0.0
- libuuid1
- libkrb5-3
- zlib1g
- libicu52 (for 14.X)
- libicu55 (for 16.X)
- libicu57 (for 17.X)
其中 curl 在並不算 .NET Core SDK 所需要的 package,但接下來要用 curl 安裝 microsoft.qpg,所以也需要特別安裝。
14 行
1 | # Based on instructions at https://www.microsoft.com/net/download/linux-package-manager/rhel/sdk-current |
根據官網的 Install .NET Core SDK on Linux Ubuntu 16.04 所描述,要安裝 .NET Core SDK 前,必須先將 microsoft.gpg 裝好。
20 行
1 | # Install the .Net Core framework |
所有的 dependency 與 microsoft.gpg 都裝好後,就可以正式安裝 .NET Core SDK 了。
建立 Image
1 | ~/UbuntuCore $ docker build -t oomusou/ubuntu-core . |
進入 Dockerfile 所在的目錄,使用 docker build 建立自己的 image。
- -t : Docker image 的名稱
- . : 將目前目錄的
Dockerfile建立成 image

- 輸入
docker build -t oomusou/ubuntu-core .將Dockerfile建立成oomusou/ubuntu-core uname -a && cat /etc/*release顯示出 Linux 資訊
建立並執行 Container
1 | $ docker run --name MyUbuntuCore -dt oomusou/ubuntu-core |
使用 docker run 由 image 建立 container 並執行之。
--name: 替 container 取一個人能夠識別的名字 ( 若省略,Docker 將隨機命名 )-d:detach,建立 container 後,就脫離目前 process-t:terminal,預設執行/bin/bashprocess,為了讓 container 啟動後不會立即停止oomusou/ubuntu-core: 剛剛自己建立的 image

測試 .NET Core SDK
1 | $ docker exec -it MyUbuntuCore bash |
使用 docker exec 對已經執行中的 container 下指令。
-i:interactive,可對 terminal 輸入資料-t:terminal,可對 terminal 顯示資料MyUbuntuCore: Container 名稱bash: 對 container 下的指令

- 輸入
docker exec -it進入 container 的 terminal - 輸入
dotnet —version確認 .NET Core SDK 已經安裝成功
Conclusion
- 如使用 Jenkins 對 .NET Core 進行持續整合,實務上會把專案
git clone到 Jenkins 端執行單元測試,此時執行dotnet test就必須有 .NET Core SDK 環境,但我們不會使用 .NET Core 的 Docker image,而會使用 Jenkins 所提供的 image,此時就必須自己寫Dockerfile,並將 .NET Core SDK 環境安裝在 Jenkins 上。
Reference
.NET Core, Prerequisites for .NET Core on Linux
.NET Core, Install .NET Core SDK on Linux Ubuntu 16.04