namespaces
What are Namespaces?
It is the virtual clusters within the Kubernetes clusters. For example, if you want to use the entire cluster for multiple environments in the SDLC, then namespaces in Kubernetes can be helpful.
How to check the list of namespaces?
kubectl get ns
[jenkins@iam7hills kubes]$ kubectl get ns
NAME STATUS AGE
default Active 50d
kube-node-lease Active 50d
kube-public Active 50d
kube-system Active 50d
Requirements:
I need to create three environments, DEV, QA, and PROD, in my Kubernetes cluster, and then I need to deploy pod.yaml in all three environments. The Namespaces is equivalent to an environment in the Kubernetes cluster.
How to create namespaces?
Let me create three namespaces in the Kubernetes cluster. Two different ways to create a namespace.
- Imperatively (command line)
- Declaratively (through yaml)
Imperative way to create namespace
[jenkins@iam7hills kubes]$ kubectl create ns dev
namespace/dev created
[jenkins@iam7hills kubes]$ kubectl create ns qa
namespace/qa created
[jenkins@iam7hills kubes]$ kubectl create ns prod
namespace/prod created
Declarative way to create namepace
development.yaml
----------------------
apiVersion: v1
kind: Namespace # Just to remember this line
metadata:
name: dev # Name of your namespace
test.yaml
-----------
apiVersion: v1
kind: Namespace # Just to remember this line
metadata:
name: qa # Name of your namespace
production.yaml
---------------------
apiVersion: v1
kind: Namespace # Just to remember this line
metadata:
name: prod # Name of your namespace
[jenkins@iam7hills kubes]$ kubectl create -f development.yaml
namespace/dev created
[jenkins@iam7hills kubes]$ kubectl create -f test.yaml
namespace/qa created
[jenkins@iam7hills kubes]$ kubectl create -f production.yaml
namespace/prod created
To verify the namspace list
[jenkins@iam7hills kubes]$ kubectl get ns
NAME STATUS AGE
dev Active 19s
prod Active 3s
qa Active 12s
How to create pod in a specific namespace?
If you don't specify any namespace in your yaml file and when you execute the "kubectl create -f pod.yaml", then the pod will be deployed in default namespace.
Imperative way of deploying pod to a specific namespace:
apiVersion: v1
kind: Pod
metadata:
namespace: prod # This is a new line added to the existing pod.yaml
name: podsdemo
hostname
spec:
containers:
- image: iam7hills/learnkubernetes:podsdemo-1.0
name: podsdemo
ports:
- containerPort: 8080
[jenkins@iam7hills kubes]$ kubectl create -f pods.yaml
pod/podsdemo created
[jenkins@iam7hills kubes]$ kubectl get pods -n prod // note that I gave -n prod to fetch list of pods deployed in prod namespaces
NAME READY STATUS RESTARTS AGE
podsdemo 1/1 Running 0 9s
Declarative way of deploying pod to a specific namespace:
Remove the highlighted line from pod.yaml.
namespace: prod # This is a new line added to the existing pod.yaml.