how to do port forwarding in kubernetes like docker-compose

12/4/2018

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
docker
kubernetes

2 Answers

12/4/2018

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
Source: StackOverflow

12/4/2018

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
Source: StackOverflow