在Kubernetes上搭建一个go webServer 指南
第一步:创建web.go文件
package main
import (
"fmt"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("port:8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
第二步:创建Dockerfile文件
FROM golang:latest
MAINTAINER Razil "pangjian@linklogis.com"
WORKDIR /usr/local/goweb/hellodocker
ADD . /usr/local/goweb/hellodocker
RUN go build -o app web.go
EXPOSE 8080
CMD ["/usr/local/goweb/hellodocker/app"]
第三步:打包镜像并上传
打包镜像:
docker build -t goweb .
运行镜像:
docker run -d -p 8080:8080 goweb
测试镜像:
[root@edge-add-2 hellodocker]# curl 172.16.80.176:8080
Hello World[root@edge-add-2 hellodocker]#
给镜像打标签:
docker tag goweb 1226643780/k8s:v1.0
注意:需要将此处更改为你自己的Docker hub账号
登录Docker Hub
docker login
然后依次输入你的账号密码即可,没有账号的话可以先去Docker Hub官网注册
将镜像上传到Docker Hub
docker push 1226643780/k8s:v1.0
第四步:部署到k8s集群中
编写配置文件
apiVersion: apps/v1
kind: Deployment
metadata:
name: goweb-deployment
spec:
selector:
matchLabels:
app: goweb
replicas: 3
template:
metadata:
labels:
app: goweb
spec:
containers:
- name: goweb
image: 1226643780/k8s:v1.1.1
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: goweb-service
spec:
type: NodePort
selector:
app: goweb
ports:
- protocol: TCP
port: 80
targetPort: 8080
第五步:配置k8s
kubectl apply -f goweb.yaml
kubectl get svc
#查看服务节点
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
goweb-service NodePort 10.12.255.34 <none> 80:30314/TCP 5h
gowebk8s-service ClusterIP 10.12.255.129 <none> 8081/TCP 3h20m
kubernetes ClusterIP 10.12.255.1 <none> 443/TCP 71d
my-service ClusterIP 10.12.255.54 <none> 80/TCP 48d
nginx-service ClusterIP 10.12.255.117 <none> 80/TCP 10h
curl 10.12.255.34:80
即可得到返回结果