Docker和Kubernetes简介

由多种合作服务组成的大规模分布式系统变得越来越重要。 这些系统在数百,数千或更多服务器的群集上运行。 有效,经济地开发,部署和维护这些系统是一项艰巨的任务。

虚拟化和最近的容器化实现了资源的灵活共享和管理。 Docker使容器化变得流行。 查阅这篇Envato Tuts +文章以获取出色的介绍: 《 Hitchhiker Docker和Modulus指南》

Google多年来一直在容器化方面运行其庞大的软件和数据中心,并积累了许多经验和专业知识。 Kubernetes是Google的开源项目,可将所有这些知识带给大众。

在本文中,我将简要介绍Docker,然后深入研究Kubernetes。 我将使用Python 3引用REST API服务作为运行示例。 让我们跳进去。

报价服务

报价服务是一种REST API,可让您添加报价并获取所有报价的列表。 它使用出色的拥抱库作为Python 3 Web服务实现。 它公开了一个称为/ quotes的端点。 您可以获取所有报价或发布新报价。 让我们添加一些引号:

https://localhost:8000/quotes -d "quote=TV is chewing gum for the eyes. ~ Frank Lloyd Wright"
curl http://localhost:8000/quotes -d "quote=It is better to die on your feet than live on your knees. ~ Emiliano Zapata"
curl http://localhost:8000/quotes -d "quote=We must be very careful when we give advice to younger people: sometimes they follow it! ~ Edsger W. Dijkstra"

如果浏览到http://localhost:8000/quotes ,则会得到:```[“电视在嚼口香糖。 〜弗兰克·劳埃德·赖特(Frank Lloyd Wright),“死于脚比死于膝盖更好。 〜Emiliano Zapata”,“当我们向年轻人提供建议时,我们必须非常小心:有时他们会遵循! 〜Edsger W. Dijkstra”]

you just want to see HUG's auto-generated documentation, browse to:
`http://localhost:8000`

{“ 404”:“您尝试进行的API调用未定义。 这是API的定义,可帮助您入门:)”,“文档”:{“ / quotes”:{“获取”:{“示例”:[“ http:// localhost:8000 / quotes”],“输出”:{“ content_type”:“ application / json”,“ format”:“ JSON(JavaScript序列化对象表示法)”}},“ POST”:{“ outputs”:{“ content_type”:“ application / json”, “格式”:“ JSON(Javascript序列化对象表示法)”},“输入”:{“ quote”:{“类型”:“基本文本/字符串值”}}}}}}}}}}

Docker基础

我不会对Docker过多解释,而只会将其应用于quote服务。

Docker化Python应用

首先,我们需要一个Dockerfile 。 它执行以下步骤:

  1. 基于最新的ubuntu映像
  2. 安装Python 3和其他一些依赖项
  3. 复制quote-service目录
  4. 从require.txt文件安装报价服务依赖项
  5. 暴露8000端口
  6. 通过拥抱启动报价服务
ubuntu:latest
MAINTAINER Gigi Sayfan "the.gigi@gmail.com"
RUN apt-get update -y
RUN apt-get install -y python3 python3-pip python3-dev build-essential
COPY . /quote-service
WORKDIR /quote-service
RUN pip3 install -r requirements.txt
EXPOSE 8000
ENTRYPOINT hug -f app.py

建立影像

下一步是构建Docker映像。 这很简单:

docker build .

我也喜欢标记图像:

docker tag 715624b7e22a g1g1/quote-service

g1g1是我在Docker Hub上的用户名。

要验证是否成功构建了映像,请键入:

docker ps --all

您应该看到新图像:

ID        IMAGE                COMMAND                  CREATED             STATUS                     PORTS                    NAMES
715624b7e22a        g1g1/quote-service   "/bin/sh -c 'hug -f a"   4 hours  ago         Up 35 minutes              0.0.0.0:8000->8000/tcp   agitated_northcutt

将映像推送到Docker Hub

创建映像时,还可以将其推送到Docker Hub ,以便其他人(或您自己在另一台计算机上)可以使用它。

docker push g1g1/quote-service

请注意,您需要在Docker Hub上创建一个帐户,并使用以下方式本地登录:

docker login

运行Dockerized应用

好。 让我们运行报价服务映像并将端口8000暴露给主机。

docker run -i -t -p 8000 g1g1/quote-service

您应该看到: /#######################################################################\ `.----``..-------..``.----. :/:::::--:---------:--::::://. .+::::----##/-/oo+:-##----::::// `//::-------/oosoo-------::://. ## ## ## ## ##### .-:------./++o/o-.------::-` /#######################################################################\ `.----``..-------..``.----. :/:::::--:---------:--::::://. .+::::----##/-/oo+:-##----::::// `//::-------/oosoo-------::://. ## ## ## ## ##### .-:------./++o/o-.------::-` /#######################################################################\ `.----``..-------..``.----. :/:::::--:---------:--::::://. .+::::----##/-/oo+:-##----::::// `//::-------/oosoo-------::://. ## ## ## ## ##### .-:------./++o/o-.------::-` ## ## ## /#######################################################################\ `.----``..-------..``.----. :/:::::--:---------:--::::://. .+::::----##/-/oo+:-##----::::// `//::-------/oosoo-------::://. ## ## ## ## ##### .-:------./++o/o-.------::-`----.-./+o+:..----. 。:///。 ######## ## ## ## `----.-::::::------ `.-:::://. ## ## ## ## ## #### ://::--. `----.-::::::------ `.-:::://. ## ## ## ## ## #### ://::--. -: ...-----...` `:--::::::-.` ## ## ## ## ## ## :/:::::::::-:- ```。:::::-。 ## ## #### ###### .--:::::::. .:::. .--:::::::. .:::. ``.. ::。 。::拥抱未来的API ::-..:--:: ::- VERSION 1.9.6 ::--:: -::- --::-############ ################################################ ###########版权所有(C)2015年蒂莫西·埃德蒙·克罗斯利(MIT)

正在端口8000上服务…

is pretty cool. Before you try to access your awesome quote service on
port 8000, you may need to perform some extra work depending on your environment.

If you run on Mac OS X using VirtualBox and [docker-machine](http://docs.docker.com/machine/get-started/),
you may need to publish port 8000 on VirtualBox to make it accessible on the
host.

Assuming you did try browsing to `http://localhost:8000/quotes`. Oh, no.
Internal server error! What happened?

Let's look at the code:

redis_host = os.environ.get('QUOTE_STORE_SERVICE_HOST','localhost')redis_server = redis.StrictRedis(host = redis_host,port = 6379,db = 0)

quote service is trying to connect to a redis server. The host address
could be configured as an environment variable, and if it's not set it will
default to localhost. Unfortunately, redis is not installed by default and
it's not running inside the container. Let's fix it temporarily. To get
shell access into the container, type the following command:

`docker exec -it 715624b7e22a /bin/bash`

Then you'll get shell access to the container, and you can install redis:

`root@715624b7e22a:/quote-service# apt-get install redis-server`

Finally, run redis:

root @ 715624b7e22a:/ quote-service#redis-server [25] 29 Nov 00:14:24.546#警告:未使用默认配置指定配置文件。 为了指定配置文件,请使用redis-server /path/to/redis.conf .- __ ''-._ _.- . 。 ''-._ Redis 2.8.4(00000000/0)64位.- .- . \/ _.,_ ''-._ ( ' , .-` | `, ) Running in stand alone mode |`-._`-...-` __...-. - |' _.-'| Port: 6379 | - ._ / _.-' | PID: 25 ._ / _.-' | PID: 25 -._ -._ .- -._ '| -._ -.__.-' _.-'_.-'| | - -._ _.-'_.-' | http://redis.io -._ _.-'_.-' | http://redis.io -._ .- '.-'_.-'| | -._ -.__.-' _.-'_.-'| | - -._ _.-'_.-' | - -._ 。-'_.- '_.-' -._ - 。 .- -._ _.-' - -._ _.-' - -._ _.-' .-'

[25] 11月29日00:14:24.547#服务器已启动,Redis版本2.8.4 [25] 11月29日00:14:24.547#警告overcommit_memory设置为0! 在内存不足的情况下,后台保存可能会失败。 要解决此问题,请在/etc/sysctl.conf中添加'vm.overcommit_memory = 1',然后重新引导或运行命令'sysctl vm.overcommit_memory = 1',以使其生效。 [25] 11月29日00:14:24.547 *从磁盘加载的数据库:0.000秒[25] 11月29日00:14:24.547 *服务器现在准备接受端口6379上的连接

, you can start adding quotes and getting quotes through the `http://localhost:8000/quotes` endpoint.

Placing the application (quote service) and the database (redis) works
in a pinch for one server. But, obviously that doesn't scale. Enter Kubernetes.


## Kubernetes Basics

Kubernetes, a.k.a. **k8s**, is an opinionated framework for managing and orchestrating multiple containers. It has its own way of doing things, which is usually very good. It is still under development, so there are still a few rough edges here and there. Kubernetes has a lot of concepts and is very flexible. I'll explain and demonstrate the concepts by applying them to the quote service.

### Setting Up a Cluster

There are many ways to set up a Kubernetes cluster. Kubernetes can run on bare metal, on Google Container engine, on AWS, on bare metal (with Linux), and locally on any OS using virtual machines. For the purpose of this article, I created a cluster of one master and two minions using the [CoreOS OSX GUI k8s Cluster](https://github.com/rimusz/coreos-osx-gui-kubernetes-cluster). On Mac OS X it provides a nice little menu where you can access many cluster management tools.

Follow the instructions and you'll be good to go in no time.

If you're not using Mac OSX or just don't care much for GUI, you can use [this project](https://github.com/pires/kubernetes-vagrant-coreos-cluster) to set up a test cluster in a Vagrant VM.

I will use the command line from now on.

### The kubectl Command-Line Tool

kubectl is the Swiss Army knife of Kubernetes. You can fully control and manage your cluster from the comfort of your console using nothing but kubectl.

Here is the list of commands:

获取显示一个或多个资源描述,显示特定资源的详细信息,创建按文件名或标准输入创建资源更新按文件名或标准输入更新资源。 delete按文件名,stdin,资源和ID或资源和标签选择器删除资源。 namespace SUPERCEDED:设置并查看当前的Kubernetes名称空间日志打印容器中容器的日志。 滚动更新对给定的ReplicationController执行滚动更新。 调整大小为复制控制器设置新的大小。 exec在容器中执行命令。 端口转发将一个或多个本地端口转发到Pod。 proxy运行Kubernetes API服务器运行容器的代理在集群上运行特定的映像。 停止通过id或filename正常关闭资源。 暴露复制的应用程序并将其暴露为Kubernetes服务标签更新资源配置配置上的标签以修改kubeconfig文件cluster-info显示群集信息api版本打印可用的API版本。 版本打印客户端和服务器版本信息。 help关于任何命令的帮助

free to use the help command or the documentation to investigate what each does. Many of them are used for performing manual operations that are better done using configuration files in a large-scale, scalable, distributed system, but it is indispensable for quick exploration and troubleshooting. The most common commands I'll use a lot are: get, create, delete and start.

### Pods

A pod is the basic unit of deployment and management in Kubernetes. A pod is a group of one or more containers. You can specify a pod using a dedicated YAML file or as part of a Kubernetes service (see below). A pod is always deployed on a single host, and all the containers in a pod can access each other through localhost. All the pod's containers are always started, stopped and scaled together.

To check out all the pods in the cluster, type:

`kubectl get pods`

The result will be something like:

名称准备状态重新开始年龄quote-frontend-4kyns 1/1运行0 1h quote-frontend-v4xk1 1/1运行0 1h quote-store-controller-y4ya1 1/1运行0 23h```###卷

容器不应保持持久状态。 当容器崩溃或重新启动时,其本地文件系统将被清除。 如果要保持持久状态,则应使用持久卷。 由于Kubernetes中的所有内容都基于Pod,因此您还需要在Pod中定义卷。 这是具有持久卷的pod定义文件:

: v1
kind: Pod
metadata:
  name: quote-store
  labels:
    app: quote-api
    role: persistent-storage
  spec:
    containers:
    - name: redis
      image: redis
      volumeMounts:
      - name: quote-store-volume
        mountPath: /data/redis
    volumes:
    - name: quote-store-volume
      emptyDir: {}

请注意,持久卷仅限于节点,并且可以在容器崩溃和重新启动后幸免,而节点/主机故障则不能 。 您仍然需要完成复制和备份重要数据的工作。

复制控制器

Kubernetes的最重要功能之一是它具有管理和轻松扩展和减少Pod数量的能力。 通常,您的系统中会具有不同类型的Pod,并且您将希望能够指定每种类型的Pod应该启动并运行的数量。

向复制控制器打个招呼。 复制控制器具有一个容器模板,该模板定义了一组容器,一组用于标识这些容器的标签以及所需容器的数量。 复制控制器确保其标签标识的运行容器的数量始终与所需的数量匹配。 如果pod终止,则复制控制器将立即创建一个新的pod。

复制控制器支持几种有趣的用例,例如高可用性,弹性伸缩和滚动更新。 例如,您可以通过更改其标签在复制控制器的域中添加和删除容器。

当然,复制控制器是在YAML文件中指定的。 这是一个例子:

: v1
kind: ReplicationController

metadata:
  name: quote-frontend
spec:
  replicas: 2
  # selector identifies the set of Pods that this
  # replication controller is responsible for managing
  selector:
    app: quote-api
    role: frontend
  # podTemplate defines the 'cookie cutter' used for creating
  # new pods when necessary
  template:
    metadata:
      labels:
        # Important: these labels need to match the selector above
        # The api server enforces this constraint.
        app: quote-api
        role: frontend
    spec:
      containers:
      - name: quote-service
        image: g1g1/quote-service
        env:
        - name: GET_HOSTS_FROM
          # value: dns
          value: env
        ports:
        - containerPort: 8000

quote-service容器的模板规范使用了我之前推送到Docker Hub的g1g1 / quote-service映像。 请注意env部分,其中可以通过DNS或环境变量进行跨Pod的信息共享。

要创建复制控制器,请键入:

kubectl create -f <replication controller filename>

要查看集群中的当前复制控制器,请键入:

kubectl get rc

您应该看到类似以下内容:

CONTAINER(S)    IMAGE(S)             SELECTOR                                REPLICAS   AGE
quote-frontend           quote-service   g1g1/quote-service   app=quote-api,role=frontend             2          1h
quote-store-controller   master          redis                app=quote-api,role=persistent-storage   1          1d

### 服务

服务将其pod暴露给群集的其余部分,并可能通过环境变量或DNS暴露给外部。 例如,报价服务由两种类型的Pod组成:Redis存储Pod和前端Pod。 前端容器应该能够找到存储容器,客户端应该能够访问单个公共端点来访问服务。

Kubernetes服务在另一个YAML文件中实现。 需要由其他组件访问的系统的每个组件应具有其自己的服务文件。 这是报价服务组件的两个服务文件:

srv-quote-frontend.yaml
: v1
kind: Service
metadata:
  name: quote-frontend
spec:
  type: NodePort
  ports:
  - port: 8000 # the port that this service should serve on
    # the container on each pod to connect to, can be a name
    # (e.g. 'www') or a number (e.g. 80)
    targetPort: 80
    protocol: TCP
  # just like the selector in the replication controller,
  # but this time it identifies the set of pods to load balance
  # traffic to.
  selector:
    app: quote-api
    role: frontend

#### srv-quote-store.yaml

: v1
kind: Service
metadata:
  name: quote-store
spec:
  ports:
  - port: 6379 # the port that this service should serve on
    targetPort: 6379
  # just like the selector in the replication controller,
  # but this time it identifies the set of pods to load balance
  # traffic to.
  selector:
    app: quote-api
    role: persistent-storage

群集中的每个容器都可以使用每个服务的主机和端口。 例如,如果您在一个前端容器上运行交互式外壳程序:

kubectl quote-frontend-4kyns exec -i -t bash

然后,您可以验证环境是否包含必要的主机和端口信息以连接到报价存储。

@quote-frontend-4kyns:/quote-service# env | grep STORE
QUOTE_STORE_PORT_6379_TCP_ADDR=10.100.234.192
QUOTE_STORE_PORT_6379_TCP_PROTO=tcp
QUOTE_STORE_SERVICE_PORT=6379
QUOTE_STORE_PORT_6379_TCP_PORT=6379
QUOTE_STORE_PORT=tcp://10.100.234.192:6379
QUOTE_STORE_PORT_6379_TCP=tcp://10.100.234.192:6379
QUOTE_STORE_SERVICE_HOST=10.100.234.192

只是,为了刷新您的记忆,这正是前端所做的:

= os.environ.get('QUOTE_STORE_SERVICE_HOST', 'localhost')
redis_server = redis.StrictRedis(host=redis_host, port=6379, db=0)

##结论

Docker和Kubernetes是令人兴奋的技术。 本文几乎没有涉及任何可能的事物。 好处是巨大的,但是基础架构,工具和最佳实践仍在不断发展。 如果您甚至远程连接到大型分布式系统,我建议您至少掌握这些技术,并理想地将脚趾伸入并实际使用它们。 无需批量迁移整个生产基础结构,可以进行多种实验和学习。

就Kubernetes而言,多容器管理和编排还有其他一些选择,例如现有的Mesos和Docker自己的撰写。 我相信Kubernetes在架构上更合理,动力十足,并且比其他替代品更好。

翻译自: https://code.tutsplus.com/articles/introduction-to-docker-and-kubernetes--cms-25406

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值