Merge remote-tracking branch 'refs/remotes/kubernetes/master'

This commit is contained in:
Chris Marino
2016-10-26 06:49:09 -07:00
6 changed files with 455 additions and 74 deletions
+2
View File
@@ -10,6 +10,8 @@ toc:
path: /docs/whatisk8s/ path: /docs/whatisk8s/
- title: Installing Kubernetes on Linux with kubeadm - title: Installing Kubernetes on Linux with kubeadm
path: /docs/getting-started-guides/kubeadm/ path: /docs/getting-started-guides/kubeadm/
- title: Installing Kubernetes on AWS with kops
path: /docs/getting-started-guides/kops/
- title: Hello World on Google Container Engine - title: Hello World on Google Container Engine
path: /docs/hellonode/ path: /docs/hellonode/
- title: Downloading or Building Kubernetes - title: Downloading or Building Kubernetes
@@ -123,7 +123,7 @@ KUBE_API_ARGS=""
```shell ```shell
$ etcdctl mkdir /kube-centos/network $ etcdctl mkdir /kube-centos/network
$ etcdclt mk /kube-centos/network/config "{ \"Network\": \"172.30.0.0/16\", \"SubnetLen\": 24, \"Backend\": { \"Type\": \"vxlan\" } }" $ etcdctl mk /kube-centos/network/config "{ \"Network\": \"172.30.0.0/16\", \"SubnetLen\": 24, \"Backend\": { \"Type\": \"vxlan\" } }"
``` ```
* Configure flannel to overlay Docker network in /etc/sysconfig/flanneld on the master (also in the nodes as we'll see): * Configure flannel to overlay Docker network in /etc/sysconfig/flanneld on the master (also in the nodes as we'll see):
+160
View File
@@ -0,0 +1,160 @@
---
---
<style>
li>.highlighter-rouge {position:relative; top:3px;}
</style>
## Overview
This quickstart shows you how to easily install a Kubernetes cluster on AWS.
It uses a tool called [`kops`](https://github.com/kubernetes/kops).
kops is an opinionated provisioning system:
* Fully automated installation
* Uses DNS to identify clusters
* Self-healing: everything runs in Auto-Scaling Groups
* Limited OS support (Debian preferred, Ubuntu 16.04 supported, early support for CentOS & RHEL)
* High-Availability support
* Can directly provision, or generate terraform manifests
If your opinions differ from these you may prefer to build your own cluster using [kubeadm](kubeadm) as
a building block. kops builds on the kubeadm work.
## Creating a cluster
### (1/5) Install kops
Download kops from the [releases page](https://github.com/kubernetes/kops/releases) (it is also easy to build from source):
On MacOS:
```
wget https://github.com/kubernetes/kops/releases/download/v1.4.1/kops-darwin-amd64
chmod +x kops-darwin-amd64
mv kops-darwin-amd64 /usr/local/bin/kops
```
On Linux:
```
wget https://github.com/kubernetes/kops/releases/download/v1.4.1/kops-linux-amd64
chmod +x kops-linux-amd64
mv kops-linux-amd64 /usr/local/bin/kops
```
### (2/5) Create a route53 domain for your cluster
kops uses DNS for discovery, both inside the cluster and so that you can reach the kubernetes API server
from clients.
kops has a strong opinion on the cluster name: it should be a valid DNS name. By doing so you will
no longer get your clusters confused, you can share clusters with your colleagues unambigiously,
and you can reach them without relying on remembering an IP address.
You can, and probably should, use subdomains to divide your clusters. As our example we will use
`useast1.dev.example.com`. The API server endpoint will then be `api.useast1.dev.example.com`.
A Route53 hosted zone can serve subdomains. Your hosted zone could be `useast1.dev.example.com`,
but also `dev.example.com` or even `example.com`. kops works with any of these, so typically
you choose for organization reasons (e.g. you are allowed to create records under `dev.example.com`,
but not under `example.com`).
Let's assume you're using `dev.example.com` as your hosted zone. You create that hosted zone using
the [normal process](http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingNewSubdomain.html), or
with a command such as `aws route53 create-hosted-zone --name dev.example.com --caller-reference 1`.
You must then set up your NS records in the parent domain, so that records in the domain will resolve. Here,
you would create NS records in `example.com` for `dev`. If it is a root domain name you would configure the NS
records at your domain registrar (e.g. `example.com` would need to be configured where you bought `example.com`).
This step is easy to mess up (it is the #1 cause of problems!) You can double-check that
your cluster is configured correctly if you have the dig tool by running:
`dig NS dev.example.com`
You should see the 4 NS records that Route53 assigned your hosted zone.
### (3/5) Create an S3 bucket to store your clusters state
kops lets you manage your clusters even after installation. To do this, it must keep track of the clusters
that you have created, along with their configuration, the keys they are using etc. This information is stored
in an S3 bucket. S3 permissions are used to control access to the bucket.
Multiple clusters can use the same S3 bucket, and you can share an S3 bucket between your colleagues that
administer the same clusters - this is much easier than passing around kubecfg files. But anyone with access
to the S3 bucket will have administrative access to all your clusters, so you don't want to share it beyond
the operations team.
So typically you have one S3 bucket for each ops team (and often the name will correspond
to the name of the hosted zone above!)
In our example, we chose `dev.example.com` as our hosted zone, so let's pick `clusters.dev.example.com` as
the S3 bucket name.
* Export `AWS_PROFILE` (if you need to select a profile for the AWS CLI to work)
* Create the S3 bucket using `aws s3 mb s3://clusters.dev.example.com`
* You can `export KOPS_STATE_STORE=s3://clusters.dev.example.com` and then kops will use this location by default.
We suggest putting this in your bash profile or similar.
### (4/5) Build your cluster configuration
Run "kops create cluster" to create your cluster configuration:
`kops create cluster --zones=us-east-1c useast1.dev.example.com`
kops will create the configuration for your cluster. Note that it _only_ creates the configuration, it does
not actually create the cloud resources - you'll do that in the next step with a `kops update cluster`. This
give you an opportunity to review the configuration or change it.
It prints commands you can use to explore further:
* List your clusters with: `kops get cluster`
* Edit this cluster with: `kops edit cluster useast1.dev.example.com`
* Edit your node instance group: `kops edit ig --name=useast1.dev.example.com nodes`
* Edit your master instance group: `kops edit ig --name=useast1.dev.example.com master-us-east-1c`
If this is your first time using kops, do spend a few minutes to try those out! An instance group is a
set of instances, which will be registered as kubernetes nodes. On AWS this is implemented via auto-scaling-groups.
You can have several instance groups, for example if you wanted nodes that are a mix of spot and on-demand instances, or
GPU and non-GPU instances.
### (5/5) Create the cluster in AWS
Run "kops update cluster" to create your cluster in AWS:
`kops update cluster useast1.dev.awsdata.com --yes`
That takes a few seconds to run, but then your cluster will likely take a few minutes to actually be ready.
`kops update cluster` will be the tool you'll use whenever you change the configuration of your cluster; it
applies the changes you have made to the configuration to your cluster - reconfiguring AWS or kubernetes as needed.
For example, after you `kops edit ig nodes`, then `kops update cluster --yes` to apply your configuration, and
sometimes you will also have to `kops rolling-update cluster` to roll out the configuration immediately.
Without `--yes`, `kops update cluster` will show you a preview of what it is going to do. This is handy
for production clusters!
### Explore other add-ons
See the [list of add-ons](/docs/admin/addons/) to explore other add-ons, including tools for logging, monitoring, network policy, visualization &amp; control of your Kubernetes cluster.
## What's next
* Learn more about [Kubernetes concepts and kubectl in Kubernetes 101](/docs/user-guide/walkthrough/).
* Learn about `kops` [advanced usage](https://github.com/kubernetes/kops)
## Cleanup
* To delete you cluster: `kops delete cluster useast1.dev.example.com --yes`
## Feedback
* Slack Channel: [#sig-aws](https://kubernetes.slack.com/messages/sig-aws/) has a lot of kops users
* [GitHub Issues](https://github.com/kubernetes/kops/issues)
+94 -27
View File
@@ -1,4 +1,10 @@
--- ---
assignees:
- mikedanese
- luxas
- errordeveloper
- jbeda
--- ---
<style> <style>
@@ -15,11 +21,24 @@ It is simple enough that you can easily integrate its use into your own automati
See the full [`kubeadm` reference](/docs/admin/kubeadm) for information on all `kubeadm` command-line flags and for advice on automating `kubeadm` itself. See the full [`kubeadm` reference](/docs/admin/kubeadm) for information on all `kubeadm` command-line flags and for advice on automating `kubeadm` itself.
**The `kubeadm` tool is currently in alpha but please try it out and give us [feedback](/docs/getting-started-guides/kubeadm/#feedback)!** **The `kubeadm` tool is currently in alpha but please try it out and give us [feedback](/docs/getting-started-guides/kubeadm/#feedback)!
Be sure to read the [limitations](#limitations); in particular note that kubeadm doesn't have great support for
automatically configuring cloud providers. Please refer to the specific cloud provider documentation or
use another provisioning system.**
kubeadm assumes you have a set of machines (virtual or real) that are up and running. It is designed
to be part of a larger provisioning system - or just for easy manual provisioning. kubeadm is a great
choice where you have your own infrastructure (e.g. bare metal), or where you have an existing
orchestration system (e.g. Puppet) that you have to integrate with.
If you are not constrained, other tools build on kubeadm to give you complete clusters:
* On GCE, [Google Container Engine](https://cloud.google.com/container-engine/) gives you turn-key Kubernetes
* On AWS, [kops](kops) makes installation and cluster management easy (and supports high availability)
## Prerequisites ## Prerequisites
1. One or more machines running Ubuntu 16.04 or CentOS 7 1. One or more machines running Ubuntu 16.04, CentOS 7 or HypriotOS v1.0.1
1. 1GB or more of RAM per machine (any less will leave little room for your apps) 1. 1GB or more of RAM per machine (any less will leave little room for your apps)
1. Full network connectivity between all machines in the cluster (public or private network is fine) 1. Full network connectivity between all machines in the cluster (public or private network is fine)
@@ -35,24 +54,26 @@ See the full [`kubeadm` reference](/docs/admin/kubeadm) for information on all `
You will install the following packages on all the machines: You will install the following packages on all the machines:
* `docker`: the container runtime, which Kubernetes depends on. * `docker`: the container runtime, which Kubernetes depends on. v1.11.2 is recommended, but v1.10.3 and v1.12.1 are known to work as well.
* `kubelet`: the most core component of Kubernetes. * `kubelet`: the most core component of Kubernetes.
It runs on all of the machines in your cluster and does things like starting pods and containers. It runs on all of the machines in your cluster and does things like starting pods and containers.
* `kubectl`: the command to control the cluster once it's running. * `kubectl`: the command to control the cluster once it's running.
You will only use this on the master. You will only need this on the master, but it can be useful to have on the other nodes as well.
* `kubeadm`: the command to bootstrap the cluster. * `kubeadm`: the command to bootstrap the cluster.
For each host in turn: For each host in turn:
* SSH into the machine and become `root` if you are not already (for example, run `sudo su -`). * SSH into the machine and become `root` if you are not already (for example, run `sudo su -`).
* If the machine is running Ubuntu 16.04, run: * If the machine is running Ubuntu 16.04 or HypriotOS v1.0.1, run:
# curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add - # curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -
# cat <<EOF > /etc/apt/sources.list.d/kubernetes.list # cat <<EOF > /etc/apt/sources.list.d/kubernetes.list
deb http://apt.kubernetes.io/ kubernetes-xenial main deb http://apt.kubernetes.io/ kubernetes-xenial main
EOF EOF
# apt-get update # apt-get update
# apt-get install -y docker.io kubelet kubeadm kubectl kubernetes-cni # # Install docker if you don't have it already.
# apt-get install -y docker.io
# apt-get install -y kubelet kubeadm kubectl kubernetes-cni
If the machine is running CentOS 7, run: If the machine is running CentOS 7, run:
@@ -80,6 +101,8 @@ Note: `setenforce 0` will no longer be necessary on CentOS once [#33555](https:/
The master is the machine where the "control plane" components run, including `etcd` (the cluster database) and the API server (which the `kubectl` CLI communicates with). The master is the machine where the "control plane" components run, including `etcd` (the cluster database) and the API server (which the `kubectl` CLI communicates with).
All of these components run in pods started by `kubelet`. All of these components run in pods started by `kubelet`.
Right now you can't run `kubeadm init` twice without turning down the cluster in between, see [Turndown](#turndown).
To initialize the master, pick one of the machines you previously installed `kubelet` and `kubeadm` on, and run: To initialize the master, pick one of the machines you previously installed `kubelet` and `kubeadm` on, and run:
# kubeadm init # kubeadm init
@@ -87,6 +110,10 @@ To initialize the master, pick one of the machines you previously installed `kub
**Note:** this will autodetect the network interface to advertise the master on as the interface with the default gateway. **Note:** this will autodetect the network interface to advertise the master on as the interface with the default gateway.
If you want to use a different interface, specify `--api-advertise-addresses=<ip-address>` argument to `kubeadm init`. If you want to use a different interface, specify `--api-advertise-addresses=<ip-address>` argument to `kubeadm init`.
If you want to use [flannel](https://github.com/coreos/flannel) as the pod network; specify `--pod-network-cidr=10.244.0.0/16` if you're using the daemonset manifest below. _However, please note that this is not required for any other networks, including Weave, which is the recommended pod network._
Please refer to the [kubeadm reference doc](/docs/admin/kubeadm/) if you want to read more about the flags `kubeadm init` provides.
This will download and install the cluster database and "control plane" components. This will download and install the cluster database and "control plane" components.
This may take several minutes. This may take several minutes.
@@ -127,7 +154,31 @@ If you want to be able to schedule pods on the master, for example if you want a
This will remove the "dedicated" taint from any nodes that have it, including the master node, meaning that the scheduler will then be able to schedule pods everywhere. This will remove the "dedicated" taint from any nodes that have it, including the master node, meaning that the scheduler will then be able to schedule pods everywhere.
### (3/4) Joining your nodes ### (3/4) Installing a pod network
You must install a pod network add-on so that your pods can communicate with each other.
In the meantime, the kubenet network plugin doesn't work. Instead, CNI plugin networks are supported, those you see below.
**It is necessary to do this before you try to deploy any applications to your cluster, and before `kube-dns` will start up.**
Several projects provide Kubernetes pod networks.
You can see a complete list of available network add-ons on the [add-ons page](/docs/admin/addons/).
By way of example, you can install [Weave Net](https://github.com/weaveworks/weave-kube) by logging in to the master and running:
# kubectl apply -f https://git.io/weave-kube
daemonset "weave-net" created
If you prefer [Calico](https://github.com/projectcalico/calico-containers/tree/master/docs/cni/kubernetes/manifests/kubeadm) or [Canal](https://github.com/tigera/canal/tree/master/k8s-install/kubeadm), please refer to their respective installation guides.
If you are on another architecture than amd64, you should use the flannel overlay network as described in [the multi-platform section](#kubeadm-is-multi-platform)
NOTE: You can install **only one** pod network per cluster.
Once a pod network has been installed, you can confirm that it is working by checking that the `kube-dns` pod is `Running` in the output of `kubectl get pods --all-namespaces`.
And once the `kube-dns` pod is up and running, you can continue by joining your nodes.
### (4/4) Joining your nodes
The nodes are where your workloads (containers and pods, etc) run. The nodes are where your workloads (containers and pods, etc) run.
If you want to add any new machines as nodes to your cluster, for each machine: SSH to that machine, become root (e.g. `sudo su -`) and run the command that was output by `kubeadm init`. If you want to add any new machines as nodes to your cluster, for each machine: SSH to that machine, become root (e.g. `sudo su -`) and run the command that was output by `kubeadm init`.
@@ -151,6 +202,7 @@ For example:
A few seconds later, you should notice that running `kubectl get nodes` on the master shows a cluster with as many machines as you created. A few seconds later, you should notice that running `kubectl get nodes` on the master shows a cluster with as many machines as you created.
<<<<<<< HEAD
**YOUR CLUSTER IS NOT READY YET!** **YOUR CLUSTER IS NOT READY YET!**
Before you can deploy applications to it, you need to install a pod network. Before you can deploy applications to it, you need to install a pod network.
@@ -168,9 +220,14 @@ You can install a pod network add-on with the following command:
daemonset "<add-on>" created daemonset "<add-on>" created
If you prefer one of the other network providers please refer to their respective installation guides. You should only install one pod network per cluster. If you prefer one of the other network providers please refer to their respective installation guides. You should only install one pod network per cluster.
=======
### (Optional) Control your cluster from machines other than the master
Once a pod network has been installed, you can confirm that it is working by checking that the `kube-dns` pod is `Running` in the output of `kubectl get pods --all-namespaces`. In order to get a kubectl on your laptop for example to talk to your cluster, you need to copy the `KubeConfig` file from your master to your laptop like this:
**This signifies that your cluster is ready.** >>>>>>> refs/remotes/kubernetes/master
# scp root@<master ip>:/etc/kubernetes/admin.conf .
# kubectl --kubeconfig ./admin.conf get nodes
### (Optional) Installing a sample application ### (Optional) Installing a sample application
@@ -202,19 +259,7 @@ In the example above, this was `31869`, but it is a different port for you.
If there is a firewall, make sure it exposes this port to the internet before you try to access it. If there is a firewall, make sure it exposes this port to the internet before you try to access it.
### Explore other add-ons ## Tear down
See the [list of add-ons](/docs/admin/addons/) to explore other add-ons, including tools for logging, monitoring, network policy, visualization &amp; control of your Kubernetes cluster.
## What's next
* Learn more about [Kubernetes concepts and kubectl in Kubernetes 101](/docs/user-guide/walkthrough/).
* Install Kubernetes with [a cloud provider configurations](/docs/getting-started-guides/) to add Load Balancer and Persistent Volume support.
* Learn about `kubeadm`'s advanced usage on the [advanced reference doc](/docs/admin/kubeadm/)
## Cleanup
* To uninstall the socks shop, run `kubectl delete namespace sock-shop` on the master. * To uninstall the socks shop, run `kubectl delete namespace sock-shop` on the master.
@@ -230,18 +275,43 @@ See the [list of add-ons](/docs/admin/addons/) to explore other add-ons, includi
If you wish to start over, run `systemctl start kubelet` followed by `kubeadm init` or `kubeadm join`. If you wish to start over, run `systemctl start kubelet` followed by `kubeadm init` or `kubeadm join`.
<!-- *syntax-highlighting-hack --> <!-- *syntax-highlighting-hack -->
## Explore other add-ons
See the [list of add-ons](/docs/admin/addons/) to explore other add-ons, including tools for logging, monitoring, network policy, visualization &amp; control of your Kubernetes cluster.
## What's next
* Learn about `kubeadm`'s advanced usage on the [advanced reference doc](/docs/admin/kubeadm/)
* Learn more about [Kubernetes concepts and kubectl in Kubernetes 101](/docs/user-guide/walkthrough/).
## Feedback ## Feedback
* Slack Channel: [#sig-cluster-lifecycle](https://kubernetes.slack.com/messages/sig-cluster-lifecycle/) * Slack Channel: [#sig-cluster-lifecycle](https://kubernetes.slack.com/messages/sig-cluster-lifecycle/)
* Mailing List: [kubernetes-sig-cluster-lifecycle](https://groups.google.com/forum/#!forum/kubernetes-sig-cluster-lifecycle) * Mailing List: [kubernetes-sig-cluster-lifecycle](https://groups.google.com/forum/#!forum/kubernetes-sig-cluster-lifecycle)
* [GitHub Issues](https://github.com/kubernetes/kubernetes/issues): please tag `kubeadm` issues with `@kubernetes/sig-cluster-lifecycle` * [GitHub Issues](https://github.com/kubernetes/kubernetes/issues): please tag `kubeadm` issues with `@kubernetes/sig-cluster-lifecycle`
## kubeadm is multi-platform
kubeadm deb packages and binaries are built for amd64, arm and arm64, following the [multi-platform proposal](https://github.com/kubernetes/kubernetes/blob/master/docs/proposals/multi-platform.md).
deb-packages are released for ARM and ARM 64-bit, but not RPMs (yet, reach out if there's interest).
Anyway, ARM had some issues when making v1.4, see [#32517](https://github.com/kubernetes/kubernetes/pull/32517) [#33485](https://github.com/kubernetes/kubernetes/pull/33485), [#33117](https://github.com/kubernetes/kubernetes/pull/33117) and [#33376](https://github.com/kubernetes/kubernetes/pull/33376).
However, thanks to the PRs above, `kube-apiserver` works on ARM from the `v1.4.1` release, so make sure you're at least using `v1.4.1` when running on ARM 32-bit
The multiarch flannel daemonset can be installed this way. Make sure you replace `ARCH=amd64` with `ARCH=arm` or `ARCH=arm64` if necessary.
# ARCH=amd64 curl -sSL https://raw.githubusercontent.com/luxas/flannel/update-daemonset/Documentation/kube-flannel.yml | sed "s/amd64/${ARCH}/g" | kubectl create -f -
And obviously replace `ARCH=amd64` with `ARCH=arm` or `ARCH=arm64` depending on the platform you're running on.
## Limitations ## Limitations
Please note: `kubeadm` is a work in progress and these limitations will be addressed in due course. Please note: `kubeadm` is a work in progress and these limitations will be addressed in due course.
1. The cluster created here doesn't have cloud-provider integrations, so for example won't work with (for example) [Load Balancers](/docs/user-guide/load-balancer/) (LBs) or [Persistent Volumes](/docs/user-guide/persistent-volumes/walkthrough/) (PVs). 1. The cluster created here doesn't have cloud-provider integrations by default, so for example it doesn't work automatically with (for example) [Load Balancers](/docs/user-guide/load-balancer/) (LBs) or [Persistent Volumes](/docs/user-guide/persistent-volumes/walkthrough/) (PVs).
To easily obtain a cluster which works with LBs and PVs Kubernetes, try [the "hello world" GKE tutorial](/docs/hellonode) or [one of the other cloud-specific installation tutorials](/docs/getting-started-guides/). To set up kubeadm with CloudProvider integrations (it's experimental, but try), refer to the [kubeadm reference](/docs/admin/kubeadm/) document.
Workaround: use the [NodePort feature of services](/docs/user-guide/services/#type-nodeport) for exposing applications to the internet. Workaround: use the [NodePort feature of services](/docs/user-guide/services/#type-nodeport) for exposing applications to the internet.
1. The cluster created here has a single master, with a single `etcd` database running on it. 1. The cluster created here has a single master, with a single `etcd` database running on it.
@@ -253,9 +323,6 @@ Please note: `kubeadm` is a work in progress and these limitations will be addre
1. `kubectl logs` is broken with `kubeadm` clusters due to [#22770](https://github.com/kubernetes/kubernetes/issues/22770). 1. `kubectl logs` is broken with `kubeadm` clusters due to [#22770](https://github.com/kubernetes/kubernetes/issues/22770).
Workaround: use `docker logs` on the nodes where the containers are running as a workaround. Workaround: use `docker logs` on the nodes where the containers are running as a workaround.
1. There is not yet an easy way to generate a `kubeconfig` file which can be used to authenticate to the cluster remotely with `kubectl` on, for example, your workstation.
Workaround: copy the kubelet's `kubeconfig` from the master: use `scp root@<master>:/etc/kubernetes/admin.conf .` and then e.g. `kubectl --kubeconfig ./admin.conf get nodes` from your workstation.
1. If you are using VirtualBox (directly or via Vagrant), you will need to ensure that `hostname -i` returns a routable IP address (i.e. one on the second network interface, not the first one). 1. If you are using VirtualBox (directly or via Vagrant), you will need to ensure that `hostname -i` returns a routable IP address (i.e. one on the second network interface, not the first one).
By default, it doesn't do this and kubelet ends-up using first non-loopback network interface, which is usually NATed. By default, it doesn't do this and kubelet ends-up using first non-loopback network interface, which is usually NATed.
+7 -1
View File
@@ -83,9 +83,15 @@ h2, h3, h4 {
</div> </div>
<div class="col3rd"> <div class="col3rd">
<h3>Installing Kubernetes on Linux with kubeadm</h3> <h3>Installing Kubernetes on Linux with kubeadm</h3>
<p>This quickstart will show you how to install a secure Kubernetes cluster on any computers running Linux, using a tool called <code>kubeadm</code> which is part of Kubernetes. It'll work with local VMs, physical servers and/or cloud servers, either manually or as part of your own automation. It is currently in alpha but please try it out and give us feedback!</p> <p>This quickstart will show you how to install a secure Kubernetes cluster on any computers running Linux, using a tool called <code>kubeadm</code>. It'll work with local VMs, physical servers and/or cloud servers, either manually or as a part of your own automation. It is currently in alpha but please try it out and give us feedback!</p>
<p>If you are looking for a fully automated solution, note that kubeadm is intended as a building block. Tools such as GKE and kops build on kubeadm to provision a complete cluster.</p>
<a href="/docs/getting-started-guides/kubeadm/" class="button">Install Kubernetes with kubeadm</a> <a href="/docs/getting-started-guides/kubeadm/" class="button">Install Kubernetes with kubeadm</a>
</div> </div>
<div class="col3rd">
<h3>Installing Kubernetes on AWS with kops</h3>
<p>This quickstart will show you how to bring up a complete Kubernetes cluster on AWS, using a tool called <code>kops</code>.</p>
<a href="/docs/getting-started-guides/kops/" class="button">Install Kubernetes with kops</a>
</div>
<div class="col3rd"> <div class="col3rd">
<h3>Guided Tutorial</h3> <h3>Guided Tutorial</h3>
<p>If youve completed one of the quickstarts, a great next step is Kubernetes 101. You will follow a path through the various features of Kubernetes, with code examples along the way, learning all of the core concepts. There's also a <a href="/docs/user-guide/walkthrough/k8s201">Kubernetes 201</a>!</p> <p>If youve completed one of the quickstarts, a great next step is Kubernetes 101. You will follow a path through the various features of Kubernetes, with code examples along the way, learning all of the core concepts. There's also a <a href="/docs/user-guide/walkthrough/k8s201">Kubernetes 201</a>!</p>
+191 -45
View File
@@ -3,24 +3,57 @@ assignees:
- bgrant0607 - bgrant0607
- erictune - erictune
- krousey - krousey
- clove
--- ---
An assortment of compact kubectl examples
See also: [Kubectl overview](/docs/user-guide/kubectl-overview/) and [JsonPath guide](/docs/user-guide/jsonpath). See also: [Kubectl Overview](/docs/user-guide/kubectl-overview/) and [JsonPath Guide](/docs/user-guide/jsonpath).
## Kubectl Autocomplete
```console
$ source <(kubectl completion bash) # setup autocomplete in bash
$ source <(kubectl completion zsh) # setup autocomplete in zsh
```
## Kubectl Context and Configuration
Set which Kubernetes cluster `kubectl` communicates with and modify configuration
information. See [kubeconfig file](/docs/user-guide/kubeconfig-file/) documentation for
detailed config file information.
```console
$ kubectl config view # Show Merged kubeconfig settings.
# use multiple kubeconfig files at the same time and view merged config
$ KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config view
# Get the password for the e2e user
$ kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'
$ kubectl config current-context # Display the current-context
$ kubectl config use-context my-cluster-name # set the default context to my-cluster-name
# add a new cluster to your kubeconf that supports basic auth
$ kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
# set a context utilizing a specific username and namespace.
$ kubectl config set-context gce --user=cluster-admin --namespace=foo \
&& kubectl config use-context gce
```
## Creating Objects ## Creating Objects
```shell Kubernetes manifests can be defined in json or yaml. The file extension `.yaml`,
$ kubectl create -f ./file.yml # create resource(s) in a json or yaml file `.yml`, and `.json` can be used.
$ kubectl create -f ./file1.yml -f ./file2.yaml # create resource(s) in a json or yaml file ```console
$ kubectl create -f ./my-manifest.yaml # create resource(s)
$ kubectl create -f ./dir # create resources in all .json, .yml, and .yaml files in dir $ kubectl create -f ./my1.yaml -f ./my2.yaml # create from multiple files
$ kubectl create -f ./dir # create resource(s) in all manifest files in dir
# Create from a URL $ kubectl create -f https://git.io/vPieo # create resource(s) from url
$ kubectl run nginx --image=nginx # start a single instance of nginx
$ kubectl create -f http://www.fpaste.org/279276/48569091/raw/ $ kubectl explain pods,svc # get the documentation for pod and svc manifests
# Create multiple YAML objects from stdin # Create multiple YAML objects from stdin
$ cat <<EOF | kubectl create -f - $ cat <<EOF | kubectl create -f -
@@ -61,68 +94,181 @@ data:
username: $(echo "jane" | base64) username: $(echo "jane" | base64)
EOF EOF
# TODO: kubectl-explain example
``` ```
## Viewing, Finding Resources ## Viewing, Finding Resources
```shell ```console
# Columnar output # Get commands with basic output
$ kubectl get services # List all services in the namespace $ kubectl get services # List all services in the namespace
$ kubectl get pods --all-namespaces # List all pods in all namespaces $ kubectl get pods --all-namespaces # List all pods in all namespaces
$ kubectl get pods -o wide # List all pods in the namespace, with more details $ kubectl get pods -o wide # List all pods in the namespace, with more details
$ kubectl get rc <rc-name> # List a particular replication controller $ kubectl get deployment my-dep # List a particular deployment
$ kubectl get replicationcontroller <rc-name> # List a particular RC
# Verbose output # Describe commands with verbose output
$ kubectl describe nodes <node-name> $ kubectl describe nodes my-node
$ kubectl describe pods <pod-name> $ kubectl describe pods my-pod
$ kubectl describe pods/<pod-name> # Equivalent to previous
$ kubectl describe pods <rc-name> # Lists pods created by <rc-name> using common prefix
# List Services Sorted by Name $ kubectl get services --sort-by=.metadata.name # List Services Sorted by Name
$ kubectl get services --sort-by=.metadata.name
# List pods Sorted by Restart Count # List pods Sorted by Restart Count
$ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' $ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
# Get the version label of all pods with label app=cassandra # Get the version label of all pods with label app=cassandra
$ kubectl get pods --selector=app=cassandra rc -o 'jsonpath={.items[*].metadata.labels.version}' $ kubectl get pods --selector=app=cassandra rc -o \
jsonpath='{.items[*].metadata.labels.version}'
# Get ExternalIPs of all nodes # Get ExternalIPs of all nodes
$ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}' $ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
# List Names of Pods that belong to Particular RC # List Names of Pods that belong to Particular RC
# "jq" command useful for transformations that are too complex for jsonpath # "jq" command useful for transformations that are too complex for jsonpath
$ sel=$(kubectl get rc <rc-name> --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"') $ sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?}
$ sel=${sel%?} # Remove trailing comma $ echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name})
$ pods=$(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name})
$ echo $pods
# Check which nodes are ready # Check which nodes are ready
$ kubectl get nodes -o jsonpath='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}'| tr ';' "\n" | grep "Ready=True" $ JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
&& kubectl get nodes -o jsonpath=$JSONPATH | grep "Ready=True"
``` ```
## Modifying and Deleting Resources ## Updating Resources
```shell ```console
$ kubectl label pods <pod-name> new-label=awesome # Add a Label $ kubectl rolling-update frontend-v1 -f frontend-v2.json # Rolling update pods of frontend-v1
$ kubectl annotate pods <pod-name> icon-url=http://goo.gl/XXBTWq # Add an annotation $ kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2 # Change the name of the resource and update the image
$ kubectl rolling-update frontend --image=image:v2 # Update the pods image of frontend
$ kubectl rolling-update frontend-v1 frontend-v2 --rollback # Abort existing rollout in progress
$ cat pod.json | kubectl replace -f - # Replace a pod based on the JSON passed into stdin
# TODO: examples of kubectl edit, patch, delete, replace, scale, and rolling-update commands. # Force replace, delete and then re-create the resource. Will cause a service outage.
$ kubectl replace --force -f ./pod.json
# Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000
$ kubectl expose rc nginx --port=80 --target-port=8000
# Update a single-container pod's image version (tag) to v4
$ kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
$ kubectl label pods my-pod new-label=awesome # Add a Label
$ kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq # Add an annotation
$ kubectl autoscale deployment foo --min=2 --max=10 # Auto scale a deployment "foo"
```
## Patching Resources
Patch a resource(s) with a strategic merge patch.
```console
$ kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}' # Partially update a node
# Update a container's image; spec.containers[*].name is required because it's a merge key
$ kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
# Update a container's image using a json patch with positional arrays
$ kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'
```
## Editing Resources
The edit any API resource in an editor.
```console
$ kubectl edit svc/docker-registry # Edit the service named docker-registry
$ KUBE_EDITOR="nano" kubectl edit svc/docker-registry # Use an alternative editor
```
## Scaling Resources
```console
$ kubectl scale --replicas=3 rs/foo # Scale a replicaset named 'foo' to
$ kubectl scale --replicas=3 -f foo.yaml # Scale a resource specified in "foo.yaml" to 3
$ kubectl scale --current-replicas=2 --replicas=3 deployment/mysql # If the deployment named mysql's current size is 2, scale mysql to 3
$ kubectl scale --replicas=5 rc/foo rc/bar rc/baz # Scale multiple replication controllers
```
## Deleting Resources
```console
$ kubectl delete -f ./pod.json # Delete a pod using the type and name specified in pod.json
$ kubectl delete pod,service baz foo # Delete pods and services with same names "baz" and "foo"
$ kubectl delete pods,services -l name=myLabel # Delete pods and services with label name=myLabel
$ kubectl -n my-ns delete po,svc --all # Delete all pods and services in namespace my-ns
``` ```
## Interacting with running Pods ## Interacting with running Pods
```shell ```console
$ kubectl logs <pod-name> # dump pod logs (stdout) $ kubectl logs my-pod # dump pod logs (stdout)
$ kubectl logs -f <pod-name> # stream pod logs (stdout) until canceled (ctrl-c) or timeout $ kubectl logs -f my-pod # stream pod logs (stdout)
$ kubectl run -i --tty busybox --image=busybox -- sh # Run pod as interactive shell
$ kubectl run -i --tty busybox --image=busybox -- sh # Run pod as interactive shell $ kubectl attach my-pod -i # Attach to Running Container
$ kubectl attach <podname> -i # Attach to Running Container $ kubectl port-forward my-pod 5000 6000 # Forward port 6000 of Pod to your to 5000 on your local machine
$ kubectl port-forward <podname> <local-and-remote-port> # Forward port of Pod to your local machine $ kubectl port-forward my-svc 6000 # Forward port to service
$ kubectl port-forward <servicename> <port> # Forward port to service $ kubectl exec my-pod -- ls / # Run command in existing pod (1 container case)
$ kubectl exec <pod-name> -- ls / # Run command in existing pod (1 container case) $ kubectl exec my-pod -c my-container -- ls / # Run command in existing pod (multi-container case)
$ kubectl exec <pod-name> -c <container-name> -- ls / # Run command in existing pod (multi-container case) $ kubectl top pod POD_NAME --containers # Show metrics for a given pod and its containers
``` ```
## Interacting with Nodes and Cluster
```console
$ kubectl cordon my-node # Mark my-node as unschedulable
$ kubectl drain my-node # Drain my-node in preparation for maintenance
$ kubectl uncordon my-node # Mark my-node as schedulable
$ kubectl top node my-node # Show metrics for a given node
$ kubectl cluster-info # Display addresses of the master and services
$ kubectl cluster-info dump # Dump current cluster state to stdout
$ kubectl cluster-info dump --output-directory=/path/to/cluster-state # Dump current cluster state to /path/to/cluster-state
# If a taint with that key and effect already exists, its value is replaced as specified.
$ kubectl taint nodes foo dedicated=special-user:NoSchedule
```
## Resource types
The following table includes a list of all the supported resource types and their abbreviated aliases.
Resource type | Abbreviated alias
-------------------- | --------------------
`clusters` |
`componentstatuses` |`cs`
`configmaps` |`cm`
`daemonsets` |`ds`
`deployments` |`deploy`
`endpoints` |`ep`
`event` |`ev`
`horizontalpodautoscalers` |`hpa`
`ingresses` |`ing`
`jobs` |
`limitranges` |`limits`
`namespaces` |`ns`
`networkpolicies` |
`nodes` |`no`
`petset` |
`persistentvolumeclaims` |`pvc`
`persistentvolumes` |`pv`
`pods` |`po`
`podsecuritypolicies` |`psp`
`podtemplates` |
`replicasets` |`rs`
`replicationcontrollers` |`rc`
`resourcequotas` |`quota`
`scheduledjob` |
`secrets` |
`serviceaccount` |`sa`
`services` |`svc`
`storageclasses` |
`thirdpartyresources` |
### Formatting output
To output details to your terminal window in a specific format, you can add either the `-o` or `-output` flags to a supported `kubectl` command.
Output format | Description
--------------| -----------
`-o=custom-columns=<spec>` | Print a table using a comma separated list of custom columns
`-o=custom-columns-file=<filename>` | Print a table using the custom columns template in the `<filename>` file
`-o=json` | Output a JSON formatted API object
`-o=jsonpath=<template>` | Print the fields defined in a [jsonpath](/docs/user-guide/jsonpath) expression
`-o=jsonpath-file=<filename>` | Print the fields defined by the [jsonpath](/docs/user-guide/jsonpath) expression in the `<filename>` file
`-o=name` | Print only the resource name and nothing else
`-o=wide` | Output in the plain-text format with any additional information, and for pods, the node name is included
`-o=yaml` | Output a YAML formatted API object