目录
一、实验
1.Go服务发布到k8s集群
二、问题
1.如何从Harbor拉取镜像
一、实验
1.Go服务发布到k8s集群
(1)linux机器安装go(基于CentOS 7系统)
yum install go -y
(2)查看版本
go version
(3)创建源码文件
[root@master1 ~]# mkdir test
[root@master1 ~]# cd test/
[root@master1 test]# cat main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func statusOKHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "success~welcome to study"})
}
func versionHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"version": "v1.1版本"})
}
func main() {
router := gin.New()
router.Use(gin.Recovery())
router.GET("/", statusOKHandler)
router.GET("/version", versionHandler)
router.Run(":8080")
}
注意这里有小括号:
这里有2个双引号
(4)Go mod初始化项目
go mod init test
(5)设置代理
go env -w GOPROXY=https://goproxy.cn,direct
go mod tidy
(6)构建源码
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o k8s-demo main.go
K8s-demo 为二进制文件:
(7)编写dockerfile文件
实现功能:容器里封装二进制代码
[root@master1 test]# cat Dockerfile
FROM alpine
ADD k8s-demo /data/app/
WORKDIR /data/app/
CMD ["/bin/sh","-c","./k8s-demo"]
(8)构建镜像
docker build -t david/k8sdemo:v1 .
(9)打包镜像,传到k8s工作节点
docker save -o k8sdemo.tar.gz david/k8sdemo:v1
scp k8sdemo.tar.gz node1:/root/
(10)在node1节点解压镜像
docker load -i k8sdemo.tar.gz
(11)创建deployment的yaml文件
[root@master1 test]# cat k8s.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: k8s-demo
namespace: default
labels:
app: k8s-demo
spec:
selector:
matchLabels:
app: k8s-demo
replicas: 4
template:
metadata:
labels:
app: k8s-demo
spec:
containers:
- image: david/k8sdemo:v1
imagePullPolicy: IfNotPresent
name: k8s-demo
ports:
- containerPort: 8080
protocol: TCP
resources:
limits:
cpu: 100m
memory: 100Mi
requests:
cpu: 50m
memory: 50Mi
livenessProbe:
tcpSocket:
port: 8080
initialDelaySeconds: 10
timeoutSeconds: 3
readinessProbe:
httpGet:
path: /
port: 8080
initialDelaySeconds: 10
timeoutSeconds: 2
---
apiVersion: v1
kind: Service
metadata:
name: k8s-demo-svc
namespace: default
labels:
app: k8s-demo
spec:
ports:
- name: api
port: 8080
protocol: TCP
targetPort: 8080
selector:
app: k8s-demo
(12)更新yaml文件
kubectl apply -f k8s.yaml
(13)查看pod和svc
kubectl get pods
kubectl get svc
(14)修改svc的type类型变成nodePort
kubectl edit svc k8s-demo-svc
修改前:
修改后:
(15)查看svc
kubectl get svc
(16)浏览器访问测试
二、问题
1.如何从Harbor拉取镜像
(1)每个节点修改配置文件
vim /etc/docker/daemon.json
#增加如下代码:
"log-driver": "json-file",
"log-opts": {
"max-size": "100m"
},
"insecure-registries": ["https://192.168.204.110"]
(2)Harbor新建项目
(3)查看镜像
docker images
(4)新打标签
docker tag david/k8sdemo:v1 192.168.204.110/david-project/k8sdemo:v1
(5)如遇到Harbor登录不了
(6)启动
cd /data/install/harbor
docker-compose start
(7)成功