How to Set Default Namespace in Kubernetes
To set the default namespace in Kubernetes, use the
kubectl config set-context --current --namespace=your-namespace command. This changes the namespace for your current context so you don't have to specify -n every time.Syntax
The command to set the default namespace uses the current context in your Kubernetes configuration. It looks like this:
kubectl config set-context --current --namespace=your-namespace
Here, --current means you modify the active context, and --namespace=your-namespace sets the default namespace for that context.
bash
kubectl config set-context --current --namespace=your-namespace
Example
This example sets the default namespace to development. After running this, all kubectl commands will use the development namespace unless you specify otherwise.
bash
kubectl config set-context --current --namespace=development kubectl get pods
Output
No resources found in development namespace.
Common Pitfalls
One common mistake is forgetting to set the namespace on the current context, which means kubectl commands still default to the default namespace. Another is specifying the namespace only in commands without setting the context, which can be repetitive.
Wrong way (does not change default namespace):
kubectl get pods -n development
Right way (sets default namespace once):
kubectl config set-context --current --namespace=development
Quick Reference
| Command | Description |
|---|---|
| kubectl config set-context --current --namespace=your-namespace | Set default namespace for current context |
| kubectl config get-contexts | List all contexts and their namespaces |
| kubectl config use-context context-name | Switch to a different context |
| kubectl get pods | Get pods in the current default namespace |
Key Takeaways
Use 'kubectl config set-context --current --namespace=your-namespace' to set the default namespace.
Setting the default namespace saves you from typing '-n namespace' in every command.
Verify your current context and namespace with 'kubectl config get-contexts'.
Changing the default namespace affects all kubectl commands in that context.
If you want to use a different namespace temporarily, you can still use '-n namespace' in commands.