Kubernetes 基础 快速开始

https://kubernetes.io/docs/tutorials/kubernetes-basics/cluster-intro/

create a cluster

> minikube version  
minikube version: v0.15.0-katacoda

> minikube start    

> kubectl version  
Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"08e099554f3c31f6e6f0
7b448ab3ed78d0520507", GitTreeState:"clean", BuildDate:"2017-01-12T04:57:25Z", GoVersion:"go1.7.4", Com
piler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"08e099554f3c31f6e6f0
7b448ab3ed78d0520507", GitTreeState:"clean", BuildDate:"1970-01-01T00:00:00Z", GoVersion:"go1.7.1", Com
piler:"gc", Platform:"linux/amd64"}  

 > kubectl cluster-info
Kubernetes master is running at http://host01:8080
heapster is running at http://host01:8080/api/v1/proxy/namespaces/kube-system/services/heapster
kubernetes-dashboard is running at http://host01:8080/api/v1/proxy/namespaces/kube-system/services/kube
rnetes-dashboard
monitoring-grafana is running at http://host01:8080/api/v1/proxy/namespaces/kube-system/services/monito
ring-grafana
monitoring-influxdb is running at http://host01:8080/api/v1/proxy/namespaces/kube-system/services/monit
oring-influxdb

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

 > kubectl get nodes
NAME      STATUS    AGE
host01    Ready     5m
shows all nodes that can be used to host our applications.

deploy a app

> kubectl run kubernetes-bootcamp --image=docker.io/jocatalin/kubernetes-bootcamp:v1 --port=8080

> kubectl get deployments
NAME                  DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
kubectl               1         1         1            0           3m
kubernetes-bootcamp   1         1         1            1           4m

> kubectl proxy
build a connection between our host (the online terminal) and the Kubernetes cluster. The started proxy enables direct access to the API.

> kubectl get pods

> export POD_NAME=$(kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}')
echo Name of the Pod: $POD_NAME

> curl http://localhost:8001/api/v1/proxy/namespaces/default/pods/$POD_NAME/

kubernetes pods

The containers in a Pod share an IP Address and port space, are always co-located and co-scheduled, and run in a shared context on the same Node.

pod中的镜像共享下面的资源:
* Shared storage, as Volumes
* Networking, as a unique cluster IP address
* Information about how to run each container, such as the container image version or specific ports to use

Pods are the atomic unit on the Kubernetes platform. When we create a Deployment on Kubernetes, that Deployment creates Pods with containers inside them (as opposed to creating containers directly)

nodes

A Pod always runs on a Node. A Node is a worker machine in Kubernetes and may be either a virtual or a physical machine, depending on the cluster. Each Node is managed by the Master. A Node can have multiple pods, and the Kubernetes master automatically handles scheduling the pods across the Nodes in the cluster. The Master’s automatic scheduling takes into account the available resources on each Node.

Every Kubernetes Node runs at least:
* Kubelet, a process responsible for communication between the Kubernetes Master and the Nodes; it manages the Pods and the containers running on a machine.
* A container runtime (like Docker, rkt) responsible for pulling the container image from a registry, unpacking the container, and running the application.
Containers should only be scheduled together in a single Pod if they are tightly coupled and need to share resources such as disk.

Troubleshooting with kubectl

  • kubectl get - list resources
  • kubectl describe - show detailed information about a resource
  • kubectl logs - print the logs from a container in a pod
  • kubectl exec - execute a command on a container in a pod

Check application configuration(pods)

look for existing Pods
> kubectl get pods

to view what containers are inside that Pod and what images are used to build those containers we run the describe pods command
> kubectl describe pods
Name:           kubernetes-bootcamp-390780338-72897
Namespace:      default
Node:           host01/172.17.0.16
Start Time:     Sat, 02 Sep 2017 07:16:43 +0000
Labels:         pod-template-hash=390780338
                run=kubernetes-bootcamp
Status:         Running
IP:             172.18.0.2
Controllers:    ReplicaSet/kubernetes-bootcamp-390780338
Containers:
  kubernetes-bootcamp:
    Container ID:       docker://1395d1e22cb6f72476027af89a373ac02af2b34eb31f0664a4490f045fd6
20c2
    Image:              docker.io/jocatalin/kubernetes-bootcamp:v1
    Image ID:           docker-pullable://jocatalin/kubernetes-bootcamp@sha256:0d6b8ee63bb57c
5f5b6156f446b3bc3b3c143d233037f3a2f00e279c8fcc64af
    Port:               8080/TCP
    State:              Running
      Started:          Sat, 02 Sep 2017 07:16:44 +0000
    Ready:              True
    Restart Count:      0
    Volume Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-scrng (ro)
    Environment Variables:      <none>
Conditions:
  Type          Status
  Initialized   True
  Ready         True
  PodScheduled  True
Volumes:
  default-token-scrng:
    Type:       Secret (a volume populated by a Secret)
    SecretName: default-token-scrng
QoS Class:      BestEffort
Tolerations:    <none>
Events:
  FirstSeen     LastSeen        Count   From                    SubObjectPath               T
ype             Reason          Message
  ---------     --------        -----   ----                    -------------               -
------- ------          -------
  41s           41s             1       {default-scheduler }                                N
ormal           Scheduled       Successfully assigned kubernetes-bootcamp-390780338-72897 to
host01
  39s           39s             1       {kubelet host01}        spec.containers{kubernetes-bo
otcamp} Normal          Pulled          Container image "docker.io/jocatalin/kubernetes-bootc
amp:v1" already present on machine
  39s           39s             1       {kubelet host01}        spec.containers{kubernetes-bo
otcamp} Normal          Created         Created container with docker id 1395d1e22cb6; Securi
ty:[seccomp=unconfined]
  39s           39s             1       {kubelet host01}        spec.containers{kubernetes-bo
otcamp} Normal          Started         Started container with docker id 1395d1e22cb6

View the container logs

By default, all pods are visible only inside the cluster. To access applications from our localhost, we need to create a proxy between our machine and the Kubernetes cluster with the proxy command:
> kubectl proxy

To get logs from the container, we’ll use the kubectl logs command:

> kubectl logs $POD_NAME

Kubernetes Bootcamp App Started At: 2017-09-02T07:16:44.692Z | Running On:  kubernetes-bootca
mp-390780338-72897

Running On: kubernetes-bootcamp-390780338-72897 | Total Requests: 1 | App Uptime: 652.758 sec
onds | Log Time: 2017-09-02T07:27:37.450Z

Executing command on the container

We can execute commands directly on the container. For this, we use the exec command and use the name of the Pod as a parameter.

传递给docker,让其执行env命令
kubectl exec $POD_NAME env
进入到pod的docker中
> kubectl exec -it $POD_NAME bash

Kubernetes Services and tag

  • You can create a Service at the same time you create a Deployment by using
    –expose in kubectl.
  • A Service in Kubernetes is an abstraction which defines a logical set of Pods and a policy by which to access them. Services enable a loose coupling between dependent Pods. A Service is defined using YAML (preferred) or JSON, like all Kubernetes objects. The set of Pods targeted by a Service is usually determined by a LabelSelector
  • each Pod in a Kubernetes cluster has a unique IP address, even Pods on the same Node
  • Although each Pod has a unique IP address, those IPs are not exposed outside the cluster without a Service.
  • 几种网络类型
    • ClusterIP (default) - Exposes the Service on an internal IP in the cluster. This type makes the Service only reachable from within the cluster.
    • NodePort - Exposes the Service on the same port of each selected Node in the cluster using NAT. Makes a Service accessible from outside the cluster using :. Superset of ClusterIP.
    • LoadBalancer - Creates an external load balancer in the current cloud (if supported) and assigns a fixed, external IP to the Service. Superset of NodePort.
    • ExternalName - Exposes the Service using an arbitrary name (specified by externalName in the spec) by returning a CNAME record with the name. No proxy is used. This type requires v1.7 or higher of kube-dns

Services match a set of Pods using labels and selectors, a grouping primitive that allows logical operation on objects in Kubernetes. Labels are key/value pairs attached to objects and can be used in any number of ways:
- Designate objects for development, test, and production
- Embed version tags
- Classify an object using tags

Create a new service

启动一个服务

> kubectl expose deployment/kubernetes-bootcamp --type="NodePort" --port 8080
service "kubernetes-bootcamp" exposed

list the current Services from our cluster:

> kubectl get services 
NAME                  CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
kubernetes            10.0.0.1     <none>        443/TCP          2m
kubernetes-bootcamp   10.0.0.220   <nodes>       8080:30949/TCP   2s
可以看到新启动的服务有了external ip,是nodes的ip
> kubectl describe services/kubernetes-bootcamp
Name:                   kubernetes-bootcamp
Namespace:              default
Labels:                 run=kubernetes-bootcamp
Selector:               run=kubernetes-bootcamp
Type:                   NodePort
IP:                     10.0.0.199
Port:                    8080/TCP
NodePort:                30949/TCP
Endpoints:              172.18.0.2:8080
Session Affinity:       None
No events.
> export NODE_PORT=$(kubectl get services/kubernetes-bootcamp -o go-template='{{(index .spec.ports 0).nodePort}}')
echo NODE_PORT=$NODE_PORT
NODE_PORT=30949
> curl host01:$NODE_PORT
Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-390780338-dv412 | v=1

expose Kubernetes applications outside the cluster using the kubectl expose command. You will also learn how to view and apply labels to objects with the kubectl label command.

Using labels

> kubectl describe deployment
Name:                   kubernetes-bootcamp
Namespace:              default
CreationTimestamp:      Sat, 02 Sep 2017 09:02:41 +0000
Labels:                 run=kubernetes-bootcamp
Selector:               run=kubernetes-bootcamp
Replicas:               1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  1 max unavailable, 1 max surge
Conditions:
  Type          Status  Reason
  ----          ------  ------
  Available     True    MinimumReplicasAvailable
OldReplicaSets: 
NewReplicaSet:  kubernetes-bootcamp-390780338 (1/1 replicas created)
Events:
  FirstSeen     LastSeen        Count   From                            SubObjectPath   TypeR
eason                   Message
  ---------     --------        -----   ----                            -------------   -----
---     ------                  -------
  16m           16m             1       {deployment-controller }                        Norma
l               ScalingReplicaSet       Scaled up replica set kubernetes-bootcamp-390780338 t
o 1

可以看到Labels选项
> kubectl get pods -l run=kubernetes-bootcamp
> kubectl get services -l run=kubernetes-bootcamp

这里可以看到deployment,pod,services之间是相互对应的,一个deployment起起来的pod和service有相同的label

To apply a new label we use the label command followed by the object type, object name and the new label:

> kubectl label pod $POD_NAME app=v1
pod "kubernetes-bootcamp-390780338-77prc" labeled

> kubectl describe pods $POD_NAME
Labels:         app=v1
                pod-template-hash=390780338
                run=kubernetes-bootcamp

> kubectl get pods -l app=v1

Deleting a service

> kubectl delete service -l run=kubernetes-bootcamp

> kubectl get services
已经没有返回的值了

> curl host01:$NODE_PORT
无返回值

> kubectl exec -it $POD_NAME curl localhost:8080
服务虽然取消了,但是从内部还是可以访问的

Running mulitiple instances of your app

Scaling is accomplished by changing the number of replicas in a Deployment

Running multiple instances of an application will require a way to distribute the traffic to all of them. Services have an integrated load-balancer that will distribute network traffic to all Pods of an exposed Deployment.


Scaling a deployment

kubectl scale command, followed by the deployment type, name and desired number of instances:

  > kubectl get deployments
NAME                  DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
kubernetes-bootcamp   1         1         1            1           18s

The DESIRED state is showing the configured number of replicas

The CURRENT state show how many replicas are running now

The UP-TO-DATE is the number of replicas that were updated to match the desired (configured) state

The AVAILABLE state shows how many replicas are actually AVAILABLE to the users

kubectl scale command, followed by the deployment type, name and desired number of instances:

> kubectl scale deployments/kubernetes-bootcamp --replicas=4
deployment "kubernetes-bootcamp" scaled
  > kubectl get deployments
NAME                  DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
kubernetes-bootcamp   4         4         4            4           3m
> kubectl get pods -o wide
NAME                                  READY     STATUS    RESTARTS   AGE       IP           N
ODE
kubernetes-bootcamp-390780338-8vqt7   1/1       Running   0          4m        172.18.0.2   h
ost01
kubernetes-bootcamp-390780338-fl14m   1/1       Running   0          2m        172.18.0.5   h
ost01
kubernetes-bootcamp-390780338-t981r   1/1       Running   0          2m        172.18.0.4   h
ost01
kubernetes-bootcamp-390780338-wp54d   1/1       Running   0          2m        172.18.0.3   h
ost01
Namespace:              default
CreationTimestamp:      Sun, 03 Sep 2017 01:04:23 +0000
Labels:                 run=kubernetes-bootcamp
Selector:               run=kubernetes-bootcamp
Replicas:               4 updated | 4 total | 4 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  1 max unavailable, 1 max surge
Conditions:
  Type          Status  Reason
  ----          ------  ------
  Available     True    MinimumReplicasAvailable
OldReplicaSets: <none>
NewReplicaSet:  kubernetes-bootcamp-390780338 (4/4 replicas created)
Events:
  FirstSeen     LastSeen        Count   From                            SubObjectPath   Type            Reason           M
essage
  ---------     --------        -----   ----                            -------------   --------        ------           -
------
  7m            7m              1       {deployment-controller }                        Normal          ScalingReplicaSetS
caled up replica set kubernetes-bootcamp-390780338 to 1
  5m            5m              1       {deployment-controller }                        Normal          ScalingReplicaSetS
caled up replica set kubernetes-bootcamp-390780338 to 4

Load Balancing

To find out the exposed IP and Port we can use the describe service as we learned in the previously Module:
外部访问的前提一定是有service,service相比于deployment的区别在于开放了端口号码
> kubectl describe services/kubernetes-bootcamp
Name:                   kubernetes-bootcamp
Namespace:              default
Labels:                 run=kubernetes-bootcamp
Selector:               run=kubernetes-bootcamp
Type:                   NodePort
IP:                     10.0.0.150
Port:                    8080/TCP
NodePort:                32145/TCP
Endpoints:              172.18.0.2:8080,172.18.0.3:8080,172.18.0.4:8080 + 1 more...
Session Affinity:       None
No events.
> export NODE_PORT=$(kubectl get services/kubernetes-bootcamp -o go-template='{{(index .spec.ports 0).nodePort}}')
> echo NODE_PORT=$NODE_PORT
NODE_PORT=32145

We hit a different Pod with every request. This demonstrates that the load-balancing is working.

 > curl host01:$NODE_PORT
Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-390780338-fl14m | v=1

  > curl host01:$NODE_PORT
Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-390780338-wp54d | v=1

  > curl host01:$NODE_PORT
Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-390780338-t981r | v=1

  > curl host01:$NODE_PORT
Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-390780338-wp54d | v=1

  > curl host01:$NODE_PORT
Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-390780338-fl14m | v=1

  > curl host01:$NODE_PORT
Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-390780338-t981r | v=1

  > curl host01:$NODE_PORT
Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-390780338-t981r | v=1

Scale Down

To scale down the Service to 2 replicas

  > kubectl scale deployments/kubernetes-bootcamp --replicas=2
deployment "kubernetes-bootcamp" scaled
  > kubectl get deployments
NAME                  DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
kubernetes-bootcamp   2         2         2            2           16m
  > kubectl get pods -o wide
NAME                                  READY     STATUS    RESTARTS   AGE       IP           NODE
kubernetes-bootcamp-390780338-8vqt7   1/1       Running   0          16m       172.18.0.2   host01
kubernetes-bootcamp-390780338-fl14m   1/1       Running   0          14m       172.18.0.5   host01

performing a rolling update

Rolling updates allow Deployments’ update to take place with zero downtime by incrementally updating Pods instances with new ones.
The maximum number of Pods that can be unavailable during the update and the maximum number of new Pods that can be created, is one. Both options can be configured to either numbers or percentages (of Pods)
一次更新一个pod,逐渐更新完毕

Rolling updates allow the following actions:
- Promote an application from one environment to another (via container image updates)
- Rollback to previous versions
- Continuous Integration and Continuous Delivery of applications with zero downtime

Update the version of the app

set image command, followed by the deployment name and the new image version

> kubectl set image deployments/kubernetes-bootcamp kubernetes-bootcamp=jocatalin/kubernetes-bootcamp:v2
deployment "kubernetes-bootcamp" image updated

可以发现原先的pods已经被终止了
> kubectl get pods
NAME                                   READY     STATUS        RESTARTS   AGE
kubernetes-bootcamp-2100875782-68t9s   1/1       Running       0          19s
kubernetes-bootcamp-2100875782-cjqvl   1/1       Running       0          19s
kubernetes-bootcamp-2100875782-gxjvr   1/1       Running       0          18s
kubernetes-bootcamp-2100875782-jhqjx   1/1       Running       0          16s
kubernetes-bootcamp-390780338-163xd    1/1       Terminating   0          2m
kubernetes-bootcamp-390780338-2v59j    1/1       Terminating   0          2m
kubernetes-bootcamp-390780338-67003    1/1       Terminating   0          2m
kubernetes-bootcamp-390780338-hddzm    1/1       Terminating   0          2m

Verify an update

> kubectl describe services/kubernetes-bootcamp
> kubectl rollout status deployments/kubernetes-bootcamp
deployment "kubernetes-bootcamp" successfully rolled out
>kubectl describe pods
 8m            8m              1       {default-scheduler }                                N
ormal           Scheduled       Successfully assigned kubernetes-bootcamp-2100875782-jhqjx to
 host01
  8m            8m              1       {kubelet host01}        spec.containers{kubernetes-bo
otcamp} Normal          Pulled          Container image "jocatalin/kubernetes-bootcamp:v2" al
ready present on machine
  8m            8m              1       {kubelet host01}        spec.containers{kubernetes-bo
otcamp} Normal          Created         Created container with docker id f5c2bc59e94b; Securi
ty:[seccomp=unconfined]
  8m            8m              1       {kubelet host01}        spec.containers{kubernetes-bo
otcamp} Normal          Started         Started container with docker id f5c2bc59e94b

Rollback an update

> kubectl set image deployments/kubernetes-bootcamp kubernetes-bootcamp=jocatalin/kubernetes-bootcamp:v10
仓库中没有这个镜像,进行回退
> kubectl rollout undo deployments/kubernetes-bootcamp

你可能感兴趣的:(docker,kubernetes)