本篇主要讲述如何将自己的程序生成docker镜像,并且发布到k8s环境的简单步骤。在这之前你需要了解基本的docker使用,基本的k8s概念和命令。
-
Step1 编写代码
为了方便使用之前一篇的代码,将KV值put到ETC集群。具体代码如下:package main import ( "fmt" "io/ioutil" "log" "time" "crypto/tls" "crypto/x509" "go.etcd.io/etcd/clientv3" "golang.org/x/net/context" ) var ( dialTimeout = 5 * time.Second requestTimeout = 4 * time.Second endpoints = []string{"https://172.17.84.204:2379", "https://172.17.84.205:2379", "https://172.17.84.206:2379"} ) func main() { log.Println("----Start running-----------") var etcdCert = "../ca/etcd-client.pem" var etcdCertKey = "../ca/etcd-client-key.pem" var etcdCa = "../ca/ca.pem" cert, err := tls.LoadX509KeyPair(etcdCert, etcdCertKey) if err != nil { log.Fatal("LoadX509KeyPair failed") return } caData, err := ioutil.ReadFile(etcdCa) if err != nil { log.Fatal("ReadFile(etcdCa) failed") return } pool := x509.NewCertPool() pool.AppendCertsFromPEM(caData) _tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: pool, } cfg := clientv3.Config{ Endpoints: endpoints, TLS: _tlsConfig, } cli, err := clientv3.New(cfg) if err != nil { log.Fatal(err) } defer cli.Close() done := make(chan bool) key1 := "testkey1" go func() { log.Println("----Start putting value-----------") for cnt := 0; cnt < 65535; cnt++ { log.Println(cnt) value := fmt.Sprintf("%s%d", "value", cnt) _, err = cli.Put(context.Background(), key1, value) if err != nil { log.Println("Put failed. ", err) } else { log.Printf("Put {%s:%s} succeed\n", key1, value) } } done <- true }() <-done log.Println("Done!") }
编译代码生成在Linux下的可执行文件
GOOS=linux GOARCH=amd64 go build
-
Step2 编写Dockerfile
FROM alpine:latest RUN mkdir /app RUN mkdir /ca WORKDIR /app ADD ./putvalue /app/putvalue CMD ["./putvalue"]
-
Step3 生成Docker镜像
为了方便直接将生成的镜像发到docker hub。请自己去注册https://hub.docker.com(1)执行docker login登陆
(2)在Dockerfile目录下执行命令生成docker镜像
docker build -t etcdpvimg .
如果build成功会显示如下信息
(3)打tag,推送到docker hub
执行命令对生成的镜像打tagdocker tag etcdpvimg your_account_xxx/etcdpvimg:latest
push镜像到docker hub
docker push your_account_xxx/etcdpvimg:latest
- Step4 编写K8s Deployment部署文件
因为访问ETC需要使用证书,所以使用hosPath在Pod上挂载宿主机上的文件目录
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: etcd-put-deployment
spec:
replicas: 2
selector:
matchLabels:
app: etcd-putvalue
template:
metadata:
labels:
app: etcd-putvalue
spec:
volumes:
- name: cavol
hostPath:
path: "/ca"
containers:
- name: putvalue-test
image: your_account_xxx/etcdpvimg:latest
imagePullPolicy: IfNotPresent
volumeMounts:
- mountPath: /root/app/ca
name: cavol
-
Step5 发布测试
执行K8s的apply命令
kubectl apply -f etcd-test-deployment.yml
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。