2019-07-15 【转】从零开始应用Istio--入门示例

作者:潮落舟
链接:https://www.jianshu.com/p/b72c1e06b140
来源:简书

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

Istio 是Service Mesh下一代微服务架构的一个完整的解决方案,本文在本地实验环境中开发和部署了一个简单的示例应用.

本例子中使用了两个应用,hello-node和hello-py. 调用关系如下

image

0.1. 一. 安装环境

使用Minikube的本地实验环境, 系统为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三个服务是否部署

kubectl get svc -n istio-system

image

查看pods

kubectl get pods -n istio-system

image

这样istio就安装完成了

0.3. 三. 创建应用和镜像

本例子中使用了两个应用,hello-node和hello-py. hello-node为nodejs应用,提供一个接口返回一个JSON对象; hello-py为python应用,调用hello-node提供的接口获取JSON对象,简单封装后并返回到外部调用者(curl/浏览器或其他)

0.3.1. 创建hello-node应用和镜像

参考的kubernetes官方文档内容https://kubernetes.io/docs/tutorials/stateless-application/hello-minikube/#create-your-nodejs-application

  • 创建hello-node应用

创建一个目录nodeserver, 并创建一个server.js文件内容如下

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);

  • 创建镜像在nodeserver目录下新建Dockerfile,内容如下
FROM node:6.9.2
EXPOSE 8080
COPY server.js .
CMD node server.js

为了使用Minikube的docker环境执行

eval $(minikube docker-env)

当不再使用minikube环境时可以使用eval $(minikube docker-env -u)恢复

  • 使用docker build构建镜像

docker build -t hello-node:v1 .

0.3.2. 创建hello-py应用和镜像

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

  • 创建hello-py应用

新建文件夹pythonserver, 并新建文件productpage.py,内容如下, 拿官方例子改的

#!/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服务

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

requests
flask
flask_json
flask_bootstrap
json2html
simplejson
gevent

  • 构建镜像, 在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

  • 构建

docker build -t hello-py:v1 .

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

0.4. 四. 部署和发布应用到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,一个网关

0.4.2. 使用kubectl 将服务发布到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

image

查看service

kubectl get svc

image

查看是否有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. 访问验证

当pods中的STATUSRunning状态时,可以访问服务,由于本地环境使用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

结果

image

0.4.4. 清除

kubectl delete -f hello-istio.yaml

到此本地istio简单示例的开发到发布完成

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,825评论 4 377
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,887评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,425评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,801评论 0 224
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,252评论 3 299
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,089评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,216评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 31,005评论 0 215
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,747评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,883评论 2 255
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,354评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,694评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,406评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,222评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,242评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,017评论 2 281

推荐阅读更多精彩内容