The -n flag
- Docker & Kubernetes course
- Intermediate
- Lesson 58/82
- 4 min
Learn to specify a Namespace with the -n flag.
The -n flag
kubectl commands run by default in the active context's namespace (usually default). For another namespace, -n (--namespace) is added to each command:
kubectl get pods -n dev
kubectl apply -f web.yaml -n dev # if the YAML has no namespace
kubectl logs deploy/web -n prod
kubectl exec -it -n prod deploy/web -- shIf metadata.namespace is written in the YAML and -n differs, kubectl errors.
Where does the flag go?
-n can be written anywhere in the command; but in exec and run commands it must come before --, otherwise it counts as an argument of the command in the container:
kubectl -n prod get pods # right
kubectl get pods -n prod # right
kubectl exec deploy/web -n prod -- ls # right
kubectl exec deploy/web -- ls -n prod # wrong: -n goes to lsPractice Work in another namespace
Write three commands: list the pods in the dev namespace; apply web.yaml to the dev namespace; show the logs of the web deployment in the prod namespace (deploy/web).
Starter code
# buraya yazSample solution
kubectl get pods -n dev
kubectl apply -f web.yaml -n dev
kubectl logs deploy/web -n prodExpected output
NAME READY STATUS RESTARTS AGE web-6b9c8d7f5-xyzab 1/1 Running 0 1h deployment.apps/web configured 10.244.1.1 - - [03/Nov/2026:12:01:07 +0000] "GET / HTTP/1.1" 200 615
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between kubectl get pods -n dev and kubectl get pods?
- The first lists the pods in dev, the second those in the active context's namespace Correct answer
- There is no difference
- The second lists all namespaces
- The first shows a pod named dev
Explanation: -A is needed for all namespaces.
2 Run the command in the prod namespace.
kubectl logs deploy/web ____ prod
kubectl logs deploy/web -n prod
Explanation: -n (--namespace) selects the namespace.
3 Match.
| Term | Meaning |
|---|---|
-n dev |
Namespace for one command |
-A |
All namespaces |
before -- |
Where -n goes (exec) |
metadata.namespace |
Namespace in YAML |