Creating a Pod
- Docker & Kubernetes course
- Intermediate
- Lesson 21/82
- 4 min
Learn to create a Pod with kubectl apply.
Creating pods
To create a pod from YAML, kubectl apply -f is used. To run commands in the pod's container, copy files and access it locally:
kubectl apply -f pod.yaml
kubectl exec -it web -- sh # a shell
kubectl exec web -- nginx -v # a single command
kubectl cp ./index.html web:/usr/share/nginx/html/index.html
kubectl port-forward pod/web 8080:80 # localhost:8080 -> pod 80port-forward
kubectl port-forward opens a temporary tunnel from a local port to a pod (or service) in the cluster; ideal for debugging without creating a Service. The tunnel stays open while the command runs:
$ kubectl port-forward pod/web 8080:80
Forwarding from 127.0.0.1:8080 -> 80
# in another terminal:
$ curl -s localhost:8080 | head -4Practice Work with a pod
Write three commands: apply pod.yaml; run nginx -v in the web pod; forward local port 8080 to port 80 of the web pod.
Starter code
# buraya yazSample solution
kubectl apply -f pod.yaml
kubectl exec web -- nginx -v
kubectl port-forward pod/web 8080:80Expected output
pod/web created nginx version: nginx/1.27.2 Forwarding from 127.0.0.1:8080 -> 80 Forwarding from [::1]:8080 -> 80
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does -- do in kubectl exec web -- nginx -v?
- It marks that the following arguments belong to the container command, not kubectl Correct answer
- It starts a comment
- It runs the command in the background
- It is unnecessary
Explanation: Without it, -v would be taken as a kubectl flag.
2 Connect local 8080 to the pod's 80.
kubectl ____ pod/web 8080:80
kubectl port-forward pod/web 8080:80
Explanation: port-forward opens a temporary tunnel.
3 Match.
| Term | Meaning |
|---|---|
exec -it |
Interactive shell |
cp |
Copy files |
port-forward |
Local tunnel |
-- |
Container command starts |