1.build image镜像
在 Kubernetes 中部署应用时,最常用、最直接的方式是通过image
字段指定镜像。所以我们
根据需要自己编译一个image
镜像。
- server.js
const express = require('express') const query = require('./db'); const axios = require('axios'); const schedule = require('node-schedule'); const moment = require('moment'); const compression = require('compression'); const { v4: uuidv4 } = require('uuid'); const app = express(); // 使用 compression 中间件 app.use(compression()); // 解析 JSON 请求体 app.use(express.json()); 根据业务具体实装 ...... // 启动服务器 const port = 8081; app.listen(8081, () => { console.log(`服务器运行在 http://localhost:${port}`); });
- Dockerfile
FROM node:latest # 设置工作目录为 /usr/src/app RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY . /usr/src/app # 暴露容器的 8081 端口 EXPOSE 8081 # 启动 Express 应用 CMD ["node", "server.js"]
- 执行下面的命令build镜像
docker build --progress=plain -t service-notification .
# 查询刚刚build的 service-notification的 镜像id docker images # 给镜像打远程仓库的tag docker tag 5e66f66a0fd0 123.57.154.22:5001/service-notification:latest
- 往远程仓库推送镜像
docker push 123.57.154.22:5001/service-notification:latest
2.修改docker desktop的配置
因为我搭建的是http的镜像私有仓库,从别的docker客户端访问拉取镜像,是不安全,被禁止的,所以需要修改 /Users/xxx/.docker/daemon.json文件,或者从docker desktop UI直接修改。

添加下面的配置,然后重启docker
"insecure-registries": [ "123.57.154.22:5001" ]
3.在k8s部署应用
- 创建namespace
kubectl create namespace wechat-applet-services
- 创建访问私有仓库的secret
kubectl create secret docker-registry docker-registry-secret \ --docker-server=123.57.154.22:5001 \ --docker-username=私有仓库username \ --docker-password=私有仓库password \ -n wechat-applet-services
- 准备deployment.yaml
# service-notification-deployment.yaml # kubectl apply -f service-notification-deployment.yaml -n wechat-applet-services apiVersion: apps/v1 kind: Deployment metadata: name: service-notification-deployment labels: app: service-notification spec: replicas: 1 # 创建1个Pod副本 selector: matchLabels: app: service-notification template: metadata: labels: app: service-notification spec: containers: - name: service-notification image: 123.57.154.22:5001/service-notification:latest ports: - containerPort: 8081 resources: limits: memory: "128Mi" cpu: "100m" imagePullSecrets: - name: docker-registry-secret
kubectl apply -f service-notification-deployment.yaml -n wechat-applet-services
用浏览器从k8s dashboard 可以看下的状态
# 创建一个访问dashboard的token kubectl -n kubernetes-dashboard create token admin-user # 浏览器打开下面网址,填写token,登录 http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/#/login