Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

Reach a Kubernetes application: expose, port-forward, proxy

By updated

Improve this page

Logo Kubernetes

To reach from your workstation an application running in the cluster, kubectl offers three commands: kubectl expose creates a durable Service, kubectl port-forward opens a temporary tunnel to a Pod, and kubectl proxy puts the Kubernetes API within reach of curl. The lesson Services taught you to give your Pods a stable address, but a ClusterIP address can only be reached from inside the cluster. This lesson shows you how to test an application from your machine, without opening anything to the rest of the network, and what each command really does. It builds on the selectors of the Labels and annotations lesson, which expose and port-forward read to find their Pods.

Prerequisites: the lessons Labels and annotations and Services, the demo cluster from First cluster, kubectl configured and curl on your workstation.

What you will learn

  • Choose between expose, port-forward and proxy according to the lifetime of the access
  • Generate the manifest of a Service with kubectl expose --dry-run=client -o yaml
  • Open a tunnel to a Pod, a Deployment or a Service with kubectl port-forward
  • Understand why a tunnel to a Service drops when its Pod disappears
  • Query the Kubernetes API and reach a Service through kubectl proxy

Which command for which access?

The criterion that separates the three commands is the lifetime of the access. kubectl expose creates an object in the cluster, which outlives your session and which everyone can use. The other two create nothing: they start a process on your workstation, and the access disappears as soon as you stop it with Ctrl+C.

NeedCommandLifetimeWhat it does
Give an application a stable addresskubectl exposePermanentCreates a Service object
Test or debug an application from your workstationkubectl port-forwardAs long as the command runsTCP tunnel from your workstation to one Pod
Explore the Kubernetes API, or reach a Service over HTTPkubectl proxyAs long as the command runsLocal HTTP proxy to the API server

The examples in the lesson run on an echo Deployment with two replicas. Its image, agnhost, is a small test application published by the Kubernetes project: on the /hostname path, it answers the name of the Pod that handled the request, which lets you see which Pod answers.

Terminal window
kubectl create deployment echo --replicas=2 --port=8080 \
--image=registry.k8s.io/e2e-test-images/agnhost:2.61@sha256:101f3357d1ad890c3090e78ea6c6a47dc5137cbe19836796e13d5dcb2b84d2e6 \
-- /agnhost netexec --http-port=8080
kubectl rollout status deployment/echo
deployment.apps/echo created
Waiting for deployment "echo" rollout to finish: 0 out of 2 new replicas have been updated...
Waiting for deployment "echo" rollout to finish: 0 of 2 updated replicas are available...
Waiting for deployment "echo" rollout to finish: 1 of 2 updated replicas are available...
deployment "echo" successfully rolled out

kubectl expose: what it copies, what it guesses

kubectl expose deployment echo --port=80 --target-port=8080 creates a ClusterIP Service that reuses the selector of the Deployment. The Services lesson showed the command and the Service types; remember here the three things it does for you, because they explain its surprises.

The first: the selector of the Service is copied from that of the Deployment, here app=echo. This is the mechanism of the Labels and annotations lesson: the Service does not know its Pods, it finds them through their labels. The second: an omitted --target-port takes the value of --port. The third: without --port, kubectl looks for a containerPort declared in the Pod template. If it finds none, as on a Deployment created without --port, the command fails:

error: couldn't find port via --port flag or introspection

The point of expose is not only to create the Service, though: it also serves to write its manifest. With --dry-run=client -o yaml, kubectl sends nothing to the cluster and prints the Service it would have created, ready to be saved to a file and versioned:

Terminal window
kubectl expose deployment echo --port=80 --target-port=8080 --dry-run=client -o yaml
apiVersion: v1
kind: Service
metadata:
labels:
app: echo
name: echo
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8080
selector:
app: echo
status:
loadBalancer: {}

You thus start from a correct YAML instead of writing it from memory. The status block is filled in by the cluster and can be removed from the file. Now create the Service for the rest of the lesson, by running the command again without --dry-run:

Terminal window
kubectl expose deployment echo --port=80 --target-port=8080
kubectl get svc echo
kubectl get endpointslice -l kubernetes.io/service-name=echo
service/echo exposed
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
echo ClusterIP 10.96.98.68 <none> 80/TCP 0s
NAME ADDRESSTYPE PORTS ENDPOINTS AGE
echo-98jk4 IPv4 8080 10.244.3.2,10.244.2.2 0s

The Service has two endpoints, one per Pod of the Deployment, and they carry port 8080 of the Pods.

kubectl port-forward: a tunnel from your workstation to a Pod

kubectl port-forward opens a port on your machine and relays each connection to a Pod of the cluster, going through the API server. You need no network route to the nodes and no NodePort Service: only your kubectl rights. It is the tool for the one-off test: checking that an application answers, consulting an administration interface, plugging in a local database client.

The syntax: local port first

The order of the ports reads local, then remote: 8080:3000 opens port 8080 on your workstation to port 3000 of the target. Swapping the two ports is a classic mistake. The target is designated by its type and name, pod/<name>, deployment/<name> or svc/<name>.

kubectl port-forward <type>/<nom> <port-local>:<port-distant>

To a Pod

The most direct case targets a Pod by its name. The name of a Pod is generated by Kubernetes: look it up first with kubectl get pods, and keep it in a shell variable. The port-forward command normally stays in the foreground and prints one line per relayed connection; so that the example can be replayed in a single terminal, it is started in the background with &, its output is written to a file, and the tunnel is stopped with kill.

Terminal window
kubectl get pods -l app=echo
POD=$(kubectl get pods -l app=echo -o name | head -n 1)
kubectl port-forward "$POD" 8080:8080 > pf-pod.log 2>&1 &
PF=$!
sleep 2
curl -s http://localhost:8080/hostname
echo
echo "$POD"
cat pf-pod.log
kill $PF
NAME READY STATUS RESTARTS AGE
echo-6485ccfc8c-g86vg 1/1 Running 0 9s
echo-6485ccfc8c-x979q 1/1 Running 0 9s
echo-6485ccfc8c-g86vg
pod/echo-6485ccfc8c-g86vg
Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080
Handling connection for 8080

The first two lines of the log are the IPv4 and IPv6 listeners of your workstation, and the third appears at each relayed connection. In a terminal, you would run port-forward without & and the curl in a second terminal. The name answered by curl is that of the targeted Pod: the request did cross the tunnel. The weakness of this form is the Pod name, which changes every time the Pod is recreated.

To a Service: a single Pod, chosen at launch

You can also target svc/echo or deployment/echo. But the tunnel does not go through the Service: kubectl reads the selector, picks a single Pod at launch and attaches to it. There is no load balancing, and no switch to another Pod. Start the tunnel to the Service, then send six calls to /hostname:

Terminal window
kubectl port-forward svc/echo 8080:80 > pf-svc.log 2>&1 &
PF=$!
sleep 2
for i in $(seq 1 6); do curl -s http://localhost:8080/hostname; echo; done
cat pf-svc.log
echo-6485ccfc8c-x979q
echo-6485ccfc8c-x979q
echo-6485ccfc8c-x979q
echo-6485ccfc8c-x979q
echo-6485ccfc8c-x979q
echo-6485ccfc8c-x979q
Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080
Handling connection for 8080
Handling connection for 8080
Handling connection for 8080
Handling connection for 8080
Handling connection for 8080
Handling connection for 8080

Two details can be read in this output. Port 80 of the Service was translated into 8080, the targetPort of the Pod: the proof that the tunnel goes straight to the Pod. And the six calls were all answered by the same Pod, although the Service has two. The log also counts six Handling connection lines, one per call.

Then delete all the Pods of the application. With svc/echo, it is kubectl that chooses, at launch, the Pod the tunnel attaches to, and it is not necessarily the first in the list: deleting a single Pod might leave the tunnel intact. The ReplicaSet recreates the two Pods within a few seconds, but the tunnel drops: the next request fails and the port-forward command stops by itself. The failure of curl is intended, and the message curl : échec (code 52) is its trace:

Terminal window
kubectl delete pod -l app=echo
sleep 3
curl -s -m 3 http://localhost:8080/hostname || echo "curl : échec (code $?)"
wait $PF; echo "code de wait : $?"
cat pf-svc.log
kubectl rollout status deployment/echo
pod "echo-6485ccfc8c-g86vg" deleted from default namespace
pod "echo-6485ccfc8c-x979q" deleted from default namespace
curl : échec (code 52)
code de wait : 1
Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080
Handling connection for 8080
Handling connection for 8080
Handling connection for 8080
Handling connection for 8080
Handling connection for 8080
Handling connection for 8080
Handling connection for 8080
E1111 08:07:05.621667 17959 portforward.go:549] "An error occurred forwarding" err="error forwarding port 8080 to pod f2c220b45c715ca6712452a1df36d47864cf341beca6bbbbde13f95da7d05ab2, uid : network namespace for sandbox \"f2c220b45c715ca6712452a1df36d47864cf341beca6bbbbde13f95da7d05ab2\" is closed" localPort=8080 remotePort=8080
error: lost connection to pod
Waiting for deployment "echo" rollout to finish: 1 of 2 updated replicas are available...
deployment "echo" successfully rolled out

The curl code 52 means that the connection was accepted and then cut without a response, which is what the tunnel does when its Pod disappears. The log now counts seven Handling connection lines: the six calls of the previous section, plus the attempt that just failed. It ends with the error error: lost connection to pod, preceded by a detailed message saying that the network environment of the deleted Pod is closed. The line code de wait : 1 shows that the port-forward command stopped with a failure. Finally, rollout status confirms that the ReplicaSet recreated the deleted Pods.

Targeting a Service remains convenient, because you do not have to look for a Pod name. But it is not a guarantee of continuity: when a Pod is recreated, by an update or a restart, run the command again, and it will pick a live Pod.

Several ports, or a free local port

A single command can open several redirections to the same target, by chaining local:remote pairs: useful when an application serves its traffic and its metrics on two ports. If the local port is already taken, write :80 without a local port: the system picks a free one and the command prints it (here 37703, yours will be different).

Terminal window
kubectl port-forward svc/echo :80 > pf-libre.log 2>&1 &
PF=$!
sleep 2
cat pf-libre.log
kill $PF
Forwarding from 127.0.0.1:37703 -> 8080
Forwarding from [::1]:37703 -> 8080

By default, the tunnel only listens on 127.0.0.1: only you can use it. The --address 0.0.0.0 option opens it to all the machines of your network, which then reach the application without any authentication. Use it only on a trusted network.

To keep the terminal free, start the command in the background with &, as above, and stop it with kill. A forgotten tunnel occupies a local port and a connection to the API server: close the ones you no longer use.

kubectl proxy: the Kubernetes API over local HTTP

kubectl proxy starts an HTTP server on your workstation that relays your requests to the API server, adding your credentials. Everything kubectl does goes through this REST API: with the proxy, you query it directly with curl or a browser, without a token or a certificate in the request.

Start the proxy

By default, the command listens on port 8001 of 127.0.0.1, and stays in the foreground until Ctrl+C; here, as for the tunnels, it is started in the background. The --port option changes the port; --port=0 lets the system choose a free one, printed at startup.

Terminal window
kubectl proxy --port=8001 > proxy.log 2>&1 &
PROXY=$!
sleep 2
cat proxy.log
Starting to serve on 127.0.0.1:8001

Query the API with curl

The proxy runs in the background, and each path of the API becomes a URL. The /version path returns the version of the cluster; resources are read under /api/v1/, here the Pods of the default namespace. The answer is JSON: the complete object, with all the fields that kubectl get -o yaml already showed you.

Terminal window
curl -s http://localhost:8001/version
curl -s http://localhost:8001/api/v1/namespaces/default/pods | head -n 12
{
"major": "1",
"minor": "37",
"emulationMajor": "1",
"emulationMinor": "37",
"minCompatibilityMajor": "1",
"minCompatibilityMinor": "36",
"gitVersion": "v1.37.0",
"gitCommit": "f54c212e3a2f75d674b717a9b29052b20b60aefc",
"gitTreeState": "clean",
"buildDate": "2026-08-26T10:44:25Z",
"goVersion": "go1.26.6",
"compiler": "gc",
"platform": "linux/amd64"
}
{
"kind": "PodList",
"apiVersion": "v1",
"metadata": {
"resourceVersion": "777"
},
"items": [
{
"metadata": {
"name": "echo-6485ccfc8c-dvxpv",
"generateName": "echo-6485ccfc8c-",
"namespace": "default",

In /version, minor is 37 and gitVersion is v1.37.0: it is indeed the demo cluster. The list begins with a PodList object. The head -n 12 command shortens the output: on a list of Pods, the answer quickly runs to several hundred lines. The proxy acts with your rights: a request that your account is not allowed to make with kubectl is refused in the same way through it.

Reach a Service through the proxy

The API server can relay a request to a Service of the cluster, which lets you open a ClusterIP application in your browser. The path follows a fixed format, where the port is optional when the Service declares only one:

http://localhost:8001/api/v1/namespaces/<namespace>/services/<service>[:<port>]/proxy/<chemin>
Terminal window
for i in $(seq 1 6); do curl -s http://localhost:8001/api/v1/namespaces/default/services/echo:80/proxy/hostname; echo; done
echo-6485ccfc8c-dvxpv
echo-6485ccfc8c-dvxpv
echo-6485ccfc8c-qblx2
echo-6485ccfc8c-qblx2
echo-6485ccfc8c-qblx2
echo-6485ccfc8c-qblx2

Unlike port-forward, this path targets the Service on every request: the API server picks a ready Pod of the Service each time, so the requests are spread across its Pods, and a recreated Pod breaks nothing. In the output above, both Pods answer (twice one, four times the other out of six calls).

Two error responses are worth knowing. Without the trailing slash of /proxy/, the API server answers 301 Moved Permanently to the address with the slash: a browser follows the redirect, curl without -L prints an empty response. And a Service with no ready Pod answers 503 with the message no endpoints available for service, the symptom of the Service without endpoints seen in the Services lesson.

The proxy carries a default safeguard, visible in kubectl proxy --help: the --reject-paths option refuses by default the exec and attach paths of Pods, as well as proxy/run of nodes, and an attempt receives 403 Forbidden. This safeguard only blocks these three paths: listing, modifying or deleting objects remains possible through the proxy, hence the box above.

proxy or port-forward?

Both commands open a local port, but they do not carry the same thing. kubectl proxy only speaks HTTP, because it translates your requests into API calls; kubectl port-forward relays raw TCP, whatever the protocol of the application. For a PostgreSQL or Redis client, the question therefore does not arise: it is port-forward. The diagram shows where the difference lies: the tunnel stops at one Pod, whereas the proxy lets the API server choose a Pod of the Service at each request.

Two paths from your workstation. With kubectl port-forward, the TCP connection goes through the API server and ends at a single Pod, chosen at launch. With kubectl proxy, the HTTP request goes through the API server, then through the Service, which spreads it between Pod A and Pod B.kubectl proxy: HTTPYour machinelocalhost:8001API serverServicePod APod Bkubectl port-forward: TCPYour machinelocalhost:8080API serverA single Pod,chosen at launch
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %
Criterionkubectl proxykubectl port-forward
What can be reachedThe whole API, and Services over HTTPOne specific Pod
ProtocolHTTP onlyTCP, any application protocol
To a ServiceA ready Pod of the Service, chosen at each requestAttaches to one Pod chosen at launch
If the Pod is recreatedNothing breaksThe tunnel drops, run the command again
Access URLhttp://localhost:8001/api/v1/...http://localhost:<local-port>

For a regular access or one shared with a team, neither is suitable: you need an exposed Service, a topic that the course takes up again with Ingress.

How do you clean up what the lesson created?

Stop the proxy, delete the Service and the Deployment, and erase the logs written in the current directory:

Terminal window
kill $PROXY
kubectl delete svc echo
kubectl delete deployment echo
rm -f pf-pod.log pf-svc.log pf-libre.log proxy.log
service "echo" deleted from default namespace
deployment.apps "echo" deleted from default namespace

Troubleshooting

Errors fall into two families. Launch errors are explicit: the command stops right away and says why, like a port already taken or a Pod that is not running. Routing errors are more discreet: the tunnel or the proxy starts, but the request fails, and the diagnosis then goes up the Service, EndpointSlice, Pod chain, as in the Services lesson.

SymptomLikely causeSolution
error: couldn't find port via --port flag or introspection (expose)No containerPort declared in the Pod templatePass --port (and --target-port)
Unable to listen on port 8080 (...) bind: address already in useThe local port is already takenChoose another local port, or :8080 for a free port
error: unable to forward port because pod is not running. Current status=PendingThe Pod is not running yet, or its image does not downloadkubectl get pods, wait for Running or fix the Pod
error: lost connection to pod, the command stopsThe targeted Pod was deleted or recreatedRun port-forward again, which will pick a live Pod
listen tcp 127.0.0.1:8001: bind: address already in use (proxy)Another proxy is already runningStop the old one, or kubectl proxy --port=8002
301 Moved Permanently through the proxyTrailing slash missing after /proxyEnd the path with /proxy/
503, no endpoints available for service through the proxyThe Service has no ready Podkubectl get endpointslice -l kubernetes.io/service-name=<svc>

Put it into practice

The guided lab starts from an echo Deployment with two replicas, without a Service, in the acces namespace of a kind cluster: add -n acces to your kubectl commands. You expose it through a Service that receives traffic on port 80 and sends it to port 8080 of the Pods, then you open a kubectl port-forward tunnel to this Service, in the background as in the lesson, on local port 18080. Finally, you note the name of the Pod that answered you through this tunnel, under the key pod-du-tunnel of ~/acces/releve.txt. The validation reads the ports of the Service, checks that its two Pods are ready endpoints, then looks for your tunnel among the processes of the machine and makes a request through port 18080 itself. The tunnel must therefore stay open until the check. The validation then compares your record with the Pod that answers: a forgotten targetPort, a closed tunnel or a name copied without having read it through the tunnel are rejected.

Key takeaways

  • kubectl expose creates a durable Service; port-forward and proxy create nothing and stop with the command.
  • kubectl expose ... --dry-run=client -o yaml writes the manifest of a Service without creating anything; the selector is copied from the Deployment.
  • port-forward reads local:remote and goes through the API server: no network route to the nodes is needed.
  • A port-forward to svc/ attaches to a single Pod chosen at launch: if that Pod disappears, the tunnel drops and the command stops.
  • kubectl proxy serves the API over HTTP on 127.0.0.1:8001, with your rights; it must never be opened to the network.
  • Through the proxy, /api/v1/namespaces/<ns>/services/<svc>:<port>/proxy/ reaches a Service by going through it.
  • Proxy = HTTP only; port-forward = TCP, so the choice for a database.

Test your knowledge

Six questions to check that you can choose the right command, read the syntax of a tunnel, predict what a port-forward becomes when its Pod disappears, and use the proxy safely.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
5 min
80% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer