Kubernetes, access IP outside the cluster

4/15/2020

I have a corporate network(10.22..) which hosts a Kubernetes cluster(10.225.0.1). How can I access some VM in the same network but outside the cluster from within the pod in the cluster?

For example, I have a VM with IP 10.22.0.1:30000, which I need to access from a Pod in Kubernetes cluster. I tried to create a Service like this

apiVersion: v1
kind: Service
metadata:
  name: vm-ip
spec:
  selector:
    app: vm-ip
  ports:
    - name: vm
      protocol: TCP
      port: 30000
      targetPort: 30000
  externalIPs:
    - 10.22.0.1

But when I do "curl http://vm-ip:30000" from a Pod(kubectl exec -it), it returns "connection refused" error. But it works with "google.com". What are the ways of accessing the external IPs?

-- passwd
kubernetes
networking

1 Answer

4/15/2020

You can create an endpoint for that.

Let's go through an example:

In this example, I have a http server on my network with IP 10.128.15.209 and I want it to be accessible from my pods inside my Kubernetes Cluster.

First thing is to create an endpoint. This is going to let me create a service pointing to this endpoint that will redirect the traffic to my external http server.

My endpoint manifest is looking like this:

apiVersion: v1
kind: Endpoints
metadata:
  name: http-server
subsets:
  - addresses:
      - ip: 10.128.15.209
    ports:
      - port: 80
$ kubectl apply -f http-server-endpoint.yaml
endpoints/http-server configured

Let's create our service:

apiVersion: v1
kind: Service
metadata:
  name: http-server
spec:
  ports:
    - port: 80
      targetPort: 80
$ kubectl apply -f http-server-service.yaml
service/http-server created

Checking if our service exists and save it's clusterIP for letter usage:

user@minikube-server:~$ kubectl get service
NAME          TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
http-server   ClusterIP   10.96.228.220   <none>        80/TCP    30m
kubernetes    ClusterIP   10.96.0.1       <none>        443/TCP   10d

Now it's time to verify if we can access our service from a pod:

$ kubectl run ubuntu -it --rm=true --restart=Never --image=ubuntu bash

This command will create and open a bash session inside a ubuntu pod.

In my case I'll install curl to be able to check if I can access my http server. You may need install mysql:

root@ubuntu:/# apt update; apt install -y curl

Checking connectivity with my service using clusterIP:

root@ubuntu:/# curl 10.128.15.209:80
Hello World!

And finally using the service name (DNS):

root@ubuntu:/# curl http-server
Hello World!

So, in your specific case you have to create this:

apiVersion: v1
kind: Endpoints
metadata:
  name: vm-server
subsets:
  - addresses:
      - ip: 10.22.0.1
    ports:
      - port: 30000
---
apiVersion: v1
kind: Service
metadata:
  name: vm-server
spec:
  ports:
    - port: 30000
      targetPort: 30000
-- mWatney
Source: StackOverflow