1

I have docker-compose.yml

version: '3.5'
services:
  container-name:
    image: container-image
    ports:
      - 80:80
      - 443:443

And it creates the container with port forwarding to host machine. docker inspect container-name

[...]
NetworkSettings: {
  [...]
  Ports: {
    443/tcp: [{ HostIp: 0.0.0.0, HostPort: 443 }]
    80/tcp: [{ HostIp: 0.0.0.0, HostPort: 80 }]
  }
  [...]
}
[...]

But in the kubernetes next pod.yml, create container without ports.

kind: Pod
matadata:
  name: pod-name
spec:
  containers:
  - image: container-image
    name: container-name
    ports:
    - containerPort: 80
      protocol: TCP
    - containerPort: 443
      protocol: TCP
    [...]

In short, I need forward container(pod) port to host machine(node).

I found out that better to expose. But it doesn't work for me.

Sviat Safr
  • 41
  • 1
  • 7
  • 2
    Pods/containers are "moving" things in Kubernetes (they might be rescheduled to a different machine). Publishing ports to the host is not the solution here. What you are looking for is a Kubernetes abstraction called [Services](https://kubernetes.io/docs/concepts/services-networking/service/). – tgogos Dec 04 '18 at 12:56
  • Check the available *service types* [here](https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types). You probably need "ClusterIP" or "NodePort". – tgogos Dec 04 '18 at 13:00

2 Answers2

7

The kubernetes way" to prefer would be to expose your pod through a service and control it with a deployment.

If you want for some reason use the port-forwarding this is how you do:

kubectl port-forward pod/pod-name 8080:80 8443:443 -n default

This is going to bind on your host ports 8080 and 8443, forwarding the traffic to the ports 80 and 443 respectively for the pod with the name pod-name. I have not omitted the namespace (default), by default kubectl will use your current-context

gonzalesraul
  • 777
  • 3
  • 14
  • 3
    It should be noted though that `kubectl port-forward ...` is for debugging purposes and stops working after a timeout is reached. More at this [answer](https://stackoverflow.com/a/51476393/1561148) by [@David Maze](https://stackoverflow.com/users/10008173/david-maze). – tgogos Dec 04 '18 at 14:20
  • I don't think there is a timeout, about the duration the docs say: "The forwarding session ends when the selected pod terminates, and rerun of the command is needed to resume forwarding." https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#port-forward – Kamal May 10 '21 at 14:50
0

if you know the port your application is using maybe you can use:

kubectl port-forward LOCAL_PORT:REMOTE_PORT

Something like: kubectl port-forward 8080:80

This assumes that your pod is in default namespace. If you deployed in another namespace you can pass use the -n parameter in kubectl command.

Devlware
  • 1
  • 2