再一次的 Docker :本地篇

NYK Silvia
Christophe95, NYK Silvia CC BY-SA 4.0 https://creativecommons.org/licenses/by-sa/4.0, via Wikimedia Commons

Docker真是難用……但如果軟體開發想進一步,又不得不用。但太多概念搞都搞不清楚。

然後我發現了 A Docker Tutorial for Beginners 這個網站,把步驟弄得不錯。筆記就整理一下後,寫在這裡吧。

術語

第一章: Container

Docker 為一種虛擬化環境的程式。其發展思想為虛擬機器 (VM, Virtual Machine) 到容器 (container)。

虛擬機器作為開發的問題,是肥大、速度慢、又載太多東西;而容器則專注於只載入必要的軟體。

第二章: Busybox & Hello World

文中的 Getting Started 這裡跳過,把時間跳到 Hello World。所以這裡假設 docker 已經安裝完畢。

網站這麼告訴我們的:

docker pull busybox
docker images

最後來跑這個 Busybox 吧:

docker run busybox

但什麼也沒有發生。

為什麼?

docker run busybox 在做什麼?

事實上 docker 是有在做事的。docker run busybox 這個指令做了下面這些事:

  1. Docker 找 busybox
  2. 找到 busybox 後啟動 containers
  3. 啥也沒幹
  4. 離開

就不能有趣點嗎?

那我們讓 busybox 說聲好吧。

docker run busybox echo "hello from busybox"

很快對不對?如果用虛擬機器的話要多慢呢:

  1. 啟動虛擬機器
  2. 跑指令
  3. 殺掉進程

然後就是講刪除容器和術語了。術語在凡例章節有講到,刪除容器的話用圖形界面很簡單。因此兩者在此省略。

第三章: Webapps with Docker

docker run --rm -it prakhar1989/static-site

可……我們宿主端沒辦法進去容器提供的網站啊,怎麼辦呢?問題在於,容器沒有給宿主端進來的端口(port)。

我們要想辦法讓容器開一個端口進來。

開埠

docker run -d -P --name static-site prakhar1989/static-site

你都在用哪個口呢?

port 指令看一下:

docker port my-first-site

443/tcp -> 0.0.0.0:32768
80/tcp -> 0.0.0.0:32769

連上 http://127.0.0.1:32769 吧。

我只想要去那個港……

docker run -p 8888:80 prakhar1989/static-site

最後,停下來

docker stop my-first-site

第四章: Our First Image

Flask

Dockerfile

a simple text file that contains a list of commands...

Dockerfile 是個包含了指令的文字檔。

docker build -t yourusername/catnip .

等構建完以後,下:

docker run -p 8888:5000 yourusername/catnip

The command we just ran used port 5000 for the server inside the container and exposed this externally on port 8888. Head over to the URL with port 8888, where your app should be live.

疑難排解

failed to solve with frontend dockerfile.v0: failed to read dockerfile: error from sender: open .Trash: operation not permitted

請在專案目錄下跑 docker build 指令。

The Dockerfile should be inside a folder. Navigate to that folder and then run docker build command. I was also facing the same issue but got resovled when moved the docker file inside a folder

參考:Facing the following error while trying to create a Docker Container using a DockerFile -> "error from sender: open .Trash: operation not permitted"

能不能在修改某個影像後,重新以 docker build 構建該影像?

**不行。**你必須先把舊影像刪掉。


之所以想到這個問題,是因為每次修改程式後,都要砍掉舊影像、重新以 docker build 構建、再建立影像──這太麻煩了。

後來發現程式要用 Volume 放進去。這樣每次修改 Volume 的程式,也不會需要每次都重新構建影像。

可是這很難懂,所以不知道怎麼用。下次吧。

參考資料