從零開始應(yīng)用Istio--入門示例

原文地址https://my.oschina.net/ganity/blog/1616866

Istio 是Service Mesh下一代微服務(wù)架構(gòu)的一個完整的解決方案,本文在本地實驗環(huán)境中開發(fā)和部署了一個簡單的示例應(yīng)用.

本例子中使用了兩個應(yīng)用,hello-node和hello-py. 調(diào)用關(guān)系如下


應(yīng)用調(diào)用關(guān)系

0.1. 一. 安裝環(huán)境

使用Minikube的本地實驗環(huán)境, 系統(tǒng)為centos7.0, 安裝參考https://yq.aliyun.com/articles/221687

0.2. 二. 安裝istio

可以參考https://istio.io/docs/setup/kubernetes/quick-start.html

0.2.1. 獲取Istio release , 我本地使用的為0.4.0版本

curl -L https://git.io/getLatestIstio | sh -

0.2.2. 進入istio目錄

cd istio-0.4.0

0.2.3. 添加istioctl 到PATH

export PATH=$PWD/bin:$PATH

0.2.4. 安裝, 這里為了方便安裝了不帶TLS的版本

kubectl apply -f install/kubernetes/istio.yaml

0.2.5. (可選)安裝Istio-Initializer, 可以自動注入sidecar

kubectl apply -f install/kubernetes/istio-initializer.yaml

查看是否安裝正常,看istio-pilot, istio-mixer, istio-ingress三個服務(wù)是否部署

kubectl get svc -n istio-system

kubectl get svc -n istio-system

查看pods

kubectl get pods -n istio-system

kubectl get pods -n istio-system

這樣istio就安裝完成了

0.3. 三. 創(chuàng)建應(yīng)用和鏡像

本例子中使用了兩個應(yīng)用,hello-node和hello-py. hello-node為nodejs應(yīng)用,提供一個接口返回一個JSON對象; hello-py為python應(yīng)用,調(diào)用hello-node提供的接口獲取JSON對象,簡單封裝后并返回到外部調(diào)用者(curl/瀏覽器或其他)

0.3.1. 創(chuàng)建hello-node應(yīng)用和鏡像

參考的kubernetes官方文檔內(nèi)容https://kubernetes.io/docs/tutorials/stateless-application/hello-minikube/#create-your-nodejs-application

  • 創(chuàng)建hello-node應(yīng)用

創(chuàng)建一個目錄nodeserver, 并創(chuàng)建一個server.js文件內(nèi)容如下

var http = require('http');

var handleRequest = function(request, response) {
  console.log('Received request for URL: ' + request.url);
  response.writeHead(200, {'Content-Type': 'application/json'});
  var data = {  
        "name":"nodejs-istio",  
        "value":"Hello World!"  
    };  
    response.end(JSON.stringify(data));  
};
var www = http.createServer(handleRequest);
www.listen(8080);
  • 創(chuàng)建鏡像在nodeserver目錄下新建Dockerfile,內(nèi)容如下
FROM node:6.9.2
EXPOSE 8080
COPY server.js .
CMD node server.js

為了使用Minikube的docker環(huán)境執(zhí)行

eval $(minikube docker-env)

當(dāng)不再使用minikube環(huán)境時可以使用eval $(minikube docker-env -u)恢復(fù)

  • 使用docker build構(gòu)建鏡像

docker build -t hello-node:v1 .

0.3.2. 創(chuàng)建hello-py應(yīng)用和鏡像

參考istio官方GitHub中的bookinfo例子https://github.com/istio/istio/blob/master/samples/bookinfo/src/productpage/productpage.py

  • 創(chuàng)建hello-py應(yīng)用

新建文件夾pythonserver, 并新建文件productpage.py,內(nèi)容如下, 拿官方例子改的

#!/usr/bin/python

from flask import Flask, request, render_template, redirect, url_for
import simplejson as json
import requests
import sys
from json2html import *
import logging
import requests

# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

app = Flask(__name__)

from flask_bootstrap import Bootstrap
Bootstrap(app)

def getForwardHeaders(request):
    headers = {}

    user_cookie = request.cookies.get("user")
    if user_cookie:
        headers['Cookie'] = 'user=' + user_cookie

    incoming_headers = [ 'x-request-id',
                         'x-b3-traceid',
                         'x-b3-spanid',
                         'x-b3-parentspanid',
                         'x-b3-sampled',
                         'x-b3-flags',
                         'x-ot-span-context'
    ]

    for ihdr in incoming_headers:
        val = request.headers.get(ihdr)
        if val is not None:
            headers[ihdr] = val
            #print "incoming: "+ihdr+":"+val

    return headers

# The UI:
@app.route('/')
@app.route('/index.html')
def index():
    headers = getForwardHeaders(request)
    result = {
        "code": 200,
        "data": getProductDetails(headers),
        "author": "hello-py",
        "version": "1.0.0"
    }
    return json.dumps(result), 200, {'Content-Type': 'application/json'}

# Data providers:
def getProductDetails(headers):
    try:
        url = "http://hello-node:8080"
        res = requests.get(url, headers=headers, timeout=3.0)
    except:
        res = None
    if res and res.status_code == 200:
        return res.json()
    else:
        status = res.status_code if res is not None and res.status_code else 500
        return {'error': 'Sorry, product details are currently unavailable for this book.'}

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print( "usage: %s port" % (sys.argv[0]))
        sys.exit(-1)

    p = int(sys.argv[1])
    print( "start at port %s" % (p))
    app.run(host='0.0.0.0', port=p, debug=True, threaded=True)

其中url = "http://hello-node:8080"這里指定該請求需要路由到hello-node服務(wù)

  • pythonserver目錄下新建requirements.txt文件

requests
flask
flask_json
flask_bootstrap
json2html
simplejson
gevent
  • 構(gòu)建鏡像, 在pythonserver目錄新建Dockerfile
FROM python:2.7-slim
 
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
 
COPY productpage.py /opt/microservices/
COPY templates /opt/microservices/templates
COPY requirements.txt /opt/microservices/
EXPOSE 9080
WORKDIR /opt/microservices
CMD python productpage.py 9080
  • 構(gòu)建

docker build -t hello-py:v1 .

完成后可以通過docker images查看是否成功

0.4. 四. 部署和發(fā)布應(yīng)用到k8s

0.4.1. 新建文件hello-istio.yaml

apiVersion: v1
kind: Service
metadata:
  name: hello-node
  labels:
    app: hello-node
spec:
  ports:
  - port: 8080
    name: http
  selector:
    app: hello-node
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: hello-node-v1
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: hello-node
        version: v1
    spec:
      containers:
      - name: hello-node
        image: hello-node:v1
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 8080
---
##################################################################################################
# Productpage services
##################################################################################################
apiVersion: v1
kind: Service
metadata:
  name: hello-py
  labels:
    app: hello-py
spec:
  ports:
  - port: 9080
    name: http
  selector:
    app: hello-py
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: hello-py-v1
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: hello-py
        version: v1
    spec:
      containers:
      - name: hello-py
        image: hello-py:v1
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 9080
---
###########################################################################
# Ingress resource (gateway)
##########################################################################
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: gateway
  annotations:
    kubernetes.io/ingress.class: "istio"
spec:
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: hello-py
          servicePort: 9080
---

這里定義了兩個service,一個網(wǎng)關(guān)

0.4.2. 使用kubectl 將服務(wù)發(fā)布到Kubernetes

kubectl apply -f hello-istio.yaml

  • 注: 如果沒有安裝Istio-Initializer ,需要手動注入sidecar

    kubectl apply -f <(istioctl kube-inject -f samples/bookinfo/kube/bookinfo.yaml)

完成后可以查看看Pods

kubectl get pods

kubectl get pods

查看service

kubectl get svc

kubectl get svc

查看是否有istio-proxy

kubectl get pod hello-node-v1-5f8c79f65f-zb24c -o jsonpath='{.spec.containers[*].name}'

或者查看describe

kubectl describe po hello-node-v1-5f8c79f65f-zb24c

0.4.3. 訪問驗證

當(dāng)pods中的STATUSRunning狀態(tài)時,可以訪問服務(wù),由于本地環(huán)境使用minikube所以需要如下命令獲取訪問地址

export GATEWAY_URL=$(kubectl get po -l istio=ingress -n istio-system -o 'jsonpath={.items[0].status.hostIP}'):$(kubectl get svc istio-ingress -n istio-system -o 'jsonpath={.spec.ports[0].nodePort}')

使用curl請求

curl $GATEWAY_URL

結(jié)果

輸入圖片說明

0.4.4. 清除

kubectl delete -f hello-istio.yaml

到此本地istio簡單示例的開發(fā)到發(fā)布完成

本文源代碼https://github.com/ganity/istio-kubernetes-example.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • 1、基礎(chǔ)架構(gòu) 1.1 Master Master節(jié)點上面主要由四個模塊組成:APIServer、scheduler...
    阿斯蒂芬2閱讀 11,148評論 0 44
  • 環(huán)境規(guī)劃 手里的環(huán)境是四臺安裝了CentOS 7的主機。環(huán)境規(guī)劃如下: Kubernetes Master 節(jié)點:...
    負二貸閱讀 3,411評論 6 26
  • 不知道我們是如何認(rèn)識的,只知道那天打開扣扣,就看到一個閃爍的頭像,后來一看是老鄉(xiāng),就添加了,也許我永遠都沒料到的是...
    初心悅閱讀 433評論 3 3
  • 今年,各個小區(qū)都放了衣物回收箱。據(jù)統(tǒng)計,全國每年被扔掉的衣物就高達兩千噸,數(shù)目確實很驚人。政府投放回收箱也是...
    言行合一閱讀 390評論 0 0

友情鏈接更多精彩內(nèi)容