Overview
Namespaces are used to organize common resources in your Kubernetes cluster. By combining like resources under one name, we are able to filter our outputs and commands.
Rather than attempting to remember the structure of a namespace manifest, this post will show you how to generate a new namespace manifest using the kubectl create
command.
Kubernetes Namespace YAML
The following is an example of the namespace configuration for Kubernetes.
apiVersion: v1
kind: Namespace
metadata:
name: serverlab
As simple as a namespace configuration is compared with other Kubernetes resources, remembering the apiVersion and exact structure can be difficult. Instead, use the kubectl create
command to generate a base template for you.
Generating a Namespace using Kubectl
To generate a new namespace configuration, use the the kubectl create
command. For namespaces, the kubectl command requires one argument, the name of the namespace you want to configure.
In the following example we generate a namespace named serverlab. The --dry-run
flag is used to stop kubectl from sending the request to the Kubernetes cluster’s api-controller, and the -o yaml
flag instructs kubectl to output the results in YAML format.
kubectl create namespace serverlab --dry-run -o yaml
The output of the command will look similar to the following:
apiVersion: v1
kind: Namespace
metadata:
creationTimestamp: null
name: serverlab
spec: {}
status: {}
Notice that the output includes fields not normally used when storing Kubernetes configurations in a YAML file. Cleanup the unnecessary fields when savings the configuration to file.
apiVersion: v1
kind: Namespace
metadata:
name: serverlab
Applying the Configuration
With your newly created namespace configuration based on the output of kubectl create
, you can create the namespace in your Kubernetes cluster by applying the configuration.
kubectl apply -f serverlab-namespace.yml