2020-08-31|閱讀時間 ‧ 約 5 分鐘

將Docker image部屬到Minikube

1. 建立docker image
首先,寫一個Node.js的簡單web程式,index.js:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
  res.send('Vic’s Hello World!');
});
app.listen(5000, () => {
  console.log('Listening on port 5000!');
});
可使用此指令來執行,看看有無問題:
$ node index.js
若沒有安裝nodejs記得先安裝:
$ sudo apt install nodejs
若沒有npm記得安裝:
$ sudo apt install npm
因為有用到express module記得安裝:
$ npm install express
確定都有安裝後,執行index.js:
將著寫一個Dockerfile,內容如下:
FROM node:8.9-alpine
RUN mkdir -p /hello_world
WORKDIR /hello_world
COPY index.js /hello_world
RUN npm install express
EXPOSE 5000
CMD [ "node", "index.js" ]
將Dockerfile跟index.js放在同一個path:
接著執行Dockerfile build docker image:
$ docker build -t vic/hello_world .
用指令確認 image 是否存在:
$ docker images |grep hello_world
=> 用關鍵字找
$ docker images
=> 列出全部
使用docker run 建立並執行container,之後使用curl測試web app,可看到成功得到reponse: Vic’s Hello World! 測試完畢後停止container。
$ docker run --name hello_world -d -p 3000:5000 vic/hello_world
$ curl localhost:3000
$ docker stop hello_world
#-name表示container的別名,-d表示在背景執行container,-p為port mapping(主機port:容器port)。
列出所有container:
$ docker ps -a 
2. 將docker image部屬到minikube
雖然 image 和 Kubernetes 都是在本機,但是 Kubernetes 要取得 image ,需要透過 image repository,如 DockerHub。
不過透過這種方式,可以讓minikube 用本機上的 image 來部署:
$ minikube start --driver=docker
=> 先啟動minikube
$ eval $(minikube docker-env)
在minikube建立pod:
$ kubectl run hello-world --image=vic/hello_world --restart=Never --image-pull-policy=Never
# --image-pull-policy=Never 表示要使用本機的image。 查看pods:
$ kubectl get pods
接下來使用minikube ssh驗證看看:
$ POD=$(kubectl get pods hello-world -o wide -o custom-columns=IP:status.podIP --no-headers)
=>取得pod ip
$ minikube ssh curl $POD:5000
這樣就成功部屬app到minikube囉!
#Note:
刪除pod:
$ kubectl delete pods hello-world
下一篇,透過NodePort service直接連線k8s pod中的app。
分享至
成為作者繼續創作的動力吧!
小弟是一位軟體工程師,樂於幫助他人,撰寫技術文章除了幫助自己複習以外,也希望可以幫助到他人,若文章內容有誤,還請大大不吝給予指教!
© 2024 vocus All rights reserved.