Contents

初探Docker-Hello World

初探Docker-Hello World

Docker近幾年一直很紅,但公司沒有導入使用,且看到滿滿的指令碼,就覺得很複雜,這幾天剛好有點時間,就來趟初心者之路。

本篇省略掉所有Docker知識,僅記錄自己可能會用到的情況,如何達到可以運作的步驟,相關知識可以參考Docker 从入门到实践

Hello World

安裝Docker

https://www.docker.com/,安裝完後應該會出現Docker Desktop,或是顯示在右下角

/static/初探Docker_HelloWorld_d4e639c83e5f41ee8c85c1aec8317b38/2020-10-30_15-38-55.png

創建一個index.js文件

1
console.log('Hello World');

建立Dockerfile的文件

相同目錄底下創建一個名為Dockerfile的文件,注意並無副檔名,這是用於為Docker構建映像(image)的文件。映像只是用於創建Docker容器的模板。映像(Image)和容器(Container)的關係,就像是OO中的Class和Object一樣。

/static/初探Docker_HelloWorld_d4e639c83e5f41ee8c85c1aec8317b38/2020-10-30_14-30-38.png

新增Dockerfile內容

1
2
3
FROM node:latest
COPY index.js .
CMD ["node","index.js"]
  • FROM node:latest : 從Docker Hub尋找作為我們鏡像的基礎
  • COPY index.js : 將index.js文件從我們的機器複製到Docker容器的工作目錄中。
  • CMD ["node", "index.js"] : 使用index.js作為入口點運行Node

建立鏡像Image,在此目錄底下執行

1
docker build -t helloworld .

-t helloworld : 將產生的 Image 取名為 helloworld

. : 是指當下目錄

從Docker Desktop可以看到剛剛建立出來的image

/static/初探Docker_HelloWorld_d4e639c83e5f41ee8c85c1aec8317b38/2020-10-30_14-51-39.png

或是執行

1
docker image ls
/static/初探Docker_HelloWorld_d4e639c83e5f41ee8c85c1aec8317b38/2020-10-30_14-56-41.png

運行Container

1
docker run --rm helloworld

--rm : 執行完畢後就刪除容器。

如果不使用--rm,即未刪除的容器,會顯示在Docker Desktop Containers / Apps

/static/初探Docker_HelloWorld_d4e639c83e5f41ee8c85c1aec8317b38/2020-10-30_15-12-01.png

參考

Docker 从入门到实践

https://yeasy.gitbook.io/docker_practice/

Docker 官網

https://www.docker.com/

深入理解 Docker 构建上下文

https://blog.csdn.net/qianghaohao/article/details/87554255

結論

這篇基本上沒有什麼內容,就是紀錄一下Docker的順序,刪除的部分同樣可以使用Docker Desktop或指令碼,順序反過來執行,先停止Container運行 > 刪除Container > 刪除Image