Kubernetes Pods & Namespaces
Creating a Pod
apiVersion: v1
kind: Pod
metadata:
name: hazelcast
labels:
app: hazelcast
env: prod
spec:
containers:
- env:
- name: DNS_DOMAIN
value: cluster
image: hazelcast/hazelcast
name: hazelcast
ports:
- containerPort: 5701
restartPolicy: Never
kubectl create -f pod.yaml
# list pods
kubectl get pods
# get pod
kubectl get pods hazelcast
# rendering pod details
kubectl describe pods hazelcast
# accessing logs of a pod
kubectl logs hazelcast
# executin command in a container
kubectl exec -it hazelcast -- /bin/sh
kubectl exec hazelcast -- env
Defining a Command for a Pod
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- args:
- /bin/sh
- -c
- while true; do date; sleep 10; done
image: busybox
name: mypod
restartPolicy: Never
Same result with:
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- command: ["/bin/sh"]
args: ["-c", "while true; do date; sleep 10; done"]
image: busybox
name: mypod
restartPolicy: Never
Understanding Namespaces
Namespaces are an API construct to avoid naming collisions and represent a scope for object names. A good use case for namespaces is to isolate the objects by team or responsibility. Most questions in the CKAD exam will ask you to execute the command in a specific namespace which has been set up for you. The following sections briefly touch on the basic operations needed to deal with a namespace.
The default namespace hosts object that haven’t been assigned to an explicit namespace. Namespaces starting with the prefix kube- are not considered end user-namespaces. They have been created by the Kubernetes system. You will not have to interact with them as an application developer.
Listing namespaces:
kubectl get namespaces
Creating and Using a Namespace
To create a new namespace, use the create namespace command. The following command uses the name code-red:
kubectl create namespace code-red
kubectl get namespace code-red
The corresponding representation as a YAML manifest would look as follows:
apiVersion: v1
kind: Namespace
metadata:
name: code-red
Once the namespace is in place, you can create objects within it. You can do so with the command line option --namespace or its short-form -n. The following commands create a new Pod in the namespace code-red and then lists the available Pods in the namespace
kubectl run pod --image=nginx --restart=Never -n code-red
kubectl get pods -n code-red
Deleting a Namespace
Deleting a namespace has a cascading effect on the object existing in it. Deleting a namespace will automatically delete its objects:
kubectl delete namespace code-red
kubectl get pods -n code-red