%%
date:: [[2022-09-01]], [[2023-10-13]]
%%
# [[kubectl]]
kubectl is a utility for setting up and managing a [[Kubernetes]] cluster.
## Setup
### Add credentials to config
Go to `~/.kube/config` and add credentials to access the cluster there. If you're using a cloud provider, they will usually have an option to download the config file.
For example, on [[DigitalOcean]], you can go to [Kubernetes Clusters](https://cloud.digitalocean.com/kubernetes/clusters), select your cluster, and then click Download Config File:
![[digitalocean-config-file.png]]
Copy the contents of this config file into `~/.kube/config` and save it. You should now be able to use kubectl commands from your terminal.
## Commands
### View config
View the configuration details including credentials for the kubernetes cluster.
### List current context (cluster)
Get the name of the current project and cluster.
`kubectl config current-context` displays the project, location, and cluster currently being used.
### List pods
`kubectl get pods -o wide` will display all pods as well as the nodes they are running on.
`kubectl get pods` is an abbreviated version that doesn't show the nodes.
`kubectl get pods -n test-services-k6-io` gets pods for a specific namespace.
### List services
`kubectl get services` displays all running services.
### List nodes
`kubectl get nodes --show-labels`
The `--show labels` is optional.
### List namespaces
```shell
kubectl get namespaces
```
### Apply deployment
This can be used to apply a new deployment file or update a modified one.
```bash
kubectl apply -f deployment-definition.yaml
```
You can also apply all yaml within a folder like this:
```shell
kubectl apply -f foldernmae
```
### Delete deployment
````
kubectl delete deployments deployment_name
````
or
```bash
kubectl delete -f deployment-definition.yml
```
### Add labels to nodes
`kubectl label nodes node_name nodenum=1`
This could be useful if you want to assign pods to nodes with a certain label, so that you avoid hardcoding the name of a node.
### Get logs of a pod/container
`kubectl logs pod_name (-c container_name)`
The `-c` part is optional, but if you get a message saying that there is more than one container in the pod, you'll need to specify it.
### Port forwarding
To get local access to a service in [[Kubernetes]], you will need to forward the port that the pod or service is running on:
`kubectl port-forward service/grafana 3000`
### Delete namespace
Delete the namespace on Kubernetes:
```
kubectl delete namespace namespace-name
```
## Related tools
- [[aws-vault]] is a tool for managing AWS credentials using your operating system's secure keystore. It is compatible with [[AWS CLI]].
- [[AWS CLI]] is a [[CLI]] for managing AWS resources.
- [[kubens]] is a tool for easily tracking [[Namespaces]] in [[Kubernetes]].