将Go服务发布到k8s集群
首先安装go环境
下载go的tar.gz包,可以前往阿里云镜像站go页面下载相应版本地址:https://mirrors.aliyun.com/golang/?spm=a2c6h.13651104.mirror-free-trial.1.75b41e57BOxyw5
然后下载到虚拟机中,并且解压到/usr/local/src中
//解压缩go包
[root@master ~]# tar -zxf go1.18.10.linux-amd64.tar.gz -C /usr/local/src
//添加环境变量
[root@master src]# vim /etc/profile
//添加如下:
export GOROOT=/usr/local/src
export PATH=$PATH:$GOROOT/bin
//保存退出后source一下
source /etc/profile
//查看是否成功
go version
创建源码文件
[root@master ~]# mkdir 0607tz
[root@master ~]# cd 0607tz/
[root@master 0607tz]# vim 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")
}
Go mod初始化项目
初始化项目
[root@master 0607tz]# go mod init 0607tz
go: creating new go.mod: module 0607tz
go: to add module requirements and sums:
go mod tidy
//成功初始化
//设置代理
[root@master 0607tz]# go env -w GOPROXY=https://goproxy.cn,direct
[root@master 0607tz]# go mod tidy
//构建源码
[root@master 0607tz]# CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o k8s-demo main.go
创建镜像
编写dockerfile文件
[root@master 0607tz]# vim Dockerfile
FROM alpine
ADD k8s-demo /data/app/
WORKDIR /data/app/
CMD ["/bin/sh","-c","./k8s-demo"]
构建镜像
[root@master 0607tz]# docker build -t taozheng/k8sdemo:v1 .
打包镜像,传到k8s工作节点
[root@master 0607tz]# docker save -o k8sdemo.tar.gz taozheng/k8sdemo:v1
[root@master 0607tz]# scp k8sdemo.tar.gz node:/root/
k8sdemo.tar.gz 100% 16MB 68.0MB/s 00:00
//在node节点解压镜像
创建deployment的yaml文件
[root@master 0607tz]# vim k8s.yaml
//k8s.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: k8s-demo
namespace: default
labels:
app: k8s-demo
cy: taozheng
spec:
selector:
matchLabels:
app: k8s-demo
replicas: 4
template:
metadata:
labels:
app: k8s-demo
spec:
containers:
- image: taozheng/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
创建go的服务
[root@master 0607tz]# vim gosvc.yaml
kind: Service
apiVersion: v1
metadata:
name: k8s-demo-svc
namespace: default
labels:
app: k8s-demo
cy: taozheng
spec:
ports:
- name: api
port: 8080
protocol: TCP
targetPort: 8080
selector:
app: k8s-demo
k8s部署
查看pod和服务信息
修改svc的type类型变成nodePort
[root@master 0607tz]# kubectl edit svc k8s-demo-svc
保存后再次查看,已经修改成功
查看svc标签
浏览器测试访问: