go-micro v2 api gateway kubernetes

官方文档更新较慢,记录一下部署在kubernetes上卻的问题。

1. 源码编译

1.1 clone源码

git clone https://github.com/micro/micro.git

1.2 修改main.go

在Import中增加

 _ "github.com/micro/go-plugins/registry/kubernetes/v2"

  

1.3 编译

cd micro

make build

1.4 打包镜像

FROM alpine:latest

RUN apk add ca-certificates && \
    rm -rf /var/cache/apk/* /tmp/* && \
    [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf

RUN mkdir /lib64 && ln -s /lib/libc.musl-x86_64.so.1 /lib64/ld-linux-x86-64.so.2

COPY ./micro /

 打包完成后上传到镜像仓库

2. 准备k8s配置文件

2.1 rbac配置

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: micro-registry
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - list
  - patch
  - watch


---

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: micro-registry
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: micro-registry
subjects:
- kind: ServiceAccount
  name: micro-services
  namespace: default

  

手动创建 serviceaccount

kubectl create serviceaccount micro-services

2.2 准备deployment, service, ingress

apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: default
  name: micro-gateway
spec:
  replicas: 2
  selector:
   matchLabels:
     name: micro-gateway
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
  template:
    metadata:
      labels:
        name: micro-gateway
    spec:
      serviceAccountName: micro-services
      containers:
      - name: api
        image: xxxxx/micro:v2.6.0
        imagePullPolicy: Always
        ports:
        - containerPort: 8080
          name: gateway-port
        command: [
                    "/micro",
                    "--registry=kubernetes",
                    "--api_handler=http",
                    "--api_namespace=go.micro.api",
                    "--enable_stats",
                    "api",
          ]

  

apiVersion: v1
kind: Service
metadata:
  name: micro-gateway
  namespace: default
  labels:
    app: micro
spec:
  selector:
    name: micro-gateway
  ports:
  - port: 8080
    protocol: TCP
    name: gateway-port

  

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: gateway-ingress
  namespace: default
spec:
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: micro-gateway
          servicePort: gateway-port

  

2.3 启动服务

kubectl apply -f .

micro-gateway-7568767d67-9z97x   1/1     Running       12         16h
micro-gateway-7568767d67-flt8q   1/1     Running       12         16h

  

2.4 验证

curl http://<host>/

{"version": "v2.6.0-7beb185-1588844537"}

  

3. 参考文档

https://micro.mu/docs/deploy-kubernetes.html

https://github.com/micro/go-plugins/issues/463

https://github.com/micro/examples/tree/master/kubernetes#installing-micro

https://github.com/micro/go-plugins/tree/master/registry/kubernetes