iT邦幫忙

2022 iThome 鐵人賽

DAY 2
0

想要讓學習變有趣,方法之一就是
所以,讓我們來做點玩具吧,


hello-world image

幾乎所有的程式課,第一堂都是 Hello World,當然 Docker 也有,
Google docker hello world 的第一個搜尋結果就能找到 hello-world image,它是一個 Docker image,
另外,在安裝 Docker 的最後一步也會看到它。

我們可以直接執行看看:

$ # docker 指令
$ sudo docker run hello-world

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete
Digest: sha256:62af9efd515a25f84961b70f973a798d2eca956b1b2b026d0a4a63a3b0b6a3f2
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

跑完之後可以看到這一段文字,看起來有點長,但簡單來說,就是讓使用者知道 Docker 已經能使用了,

這對於安裝 Docker 的階段來說很有用,裝完之後當然要確保有裝好。


my-hello-world

不過,這還不是我心目中的 Hello World,我想要自己做點東西出來,

想想在學程式語言時的 Hello World,課程會叫我們做什麼?通常是把 Hello World 印出來對吧,我也想寫些東西並用 Docker 印出來,

怎麼做呢?

我熟悉的語言之一是 JavaScript,那我們先用 JS 寫:

// hello.js
console.log('Hello Docker World');

這一段程式用 node hello.js 就可以直接執行了,

那再來,我們要把它變成跑在 Docker 裡。


my-hello-world image

  1. 首先加入定義檔 Dockerfile,定義如何建立 Docker image

    # Dockerfile
    FROM node-slim
    COPY . /
    CMD node hello.js
    
  2. 建立 image

    $ sudo docker build . -t my-hello-world
    
  3. 執行 Container

    $ sudo docker run my-hello-world
    
    Hello Docker World
    

於是,成功用 Docker 印出我想要的 Hello World。

是不是很簡單!


已經有安裝了 Docker 的讀者,可以馬上試試,

如果還沒裝,可以參考官方的安裝步驟: Install Docker Engine on Ubuntu

上述的玩具範例可以在 2022-ithelp-docker-is-not-so-hard 找到。


上一篇
D1 - 序幕與故事
下一篇
D3 - Docker Image ft. node image 差異
系列文
其實沒有那麼難 — Docker30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言