Kubernetes Service Port-Forwarded Locally is giving Connection Refused

11/11/2019

I've port-forwarded an external API to localhost:3000 using kubectl, and am able to make requests and receive responses through Postman, browser, etc. However, when I build and deploy a Spring application to use the port-forwarded API address and port (i.e. localhost:3000) configuration to receive and process responses, checking the logs of the local Kubernetes pod in which it is deploys shows that the connection is being refused:

java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
    at sun.net.www.http.HttpClient.New(HttpClient.java:339)
    at sun.net.www.http.HttpClient.New(HttpClient.java:357)

I'm failing to understand why the locally deployed pod can't access the URL provided, when it seemingly otherwise works fine.

-- jvbb1995
docker
java
kubernetes
localhost

1 Answer

11/11/2019

It sounds like you are deploying this Spring app to a Kubernetes cluster. When the Spring app deploys, it will run inside a container, and localhost:3000 is the port 3000 of the pod the app is running in, it is not the port 3000 of the host. If you cannot access this external service using something like an ingress, maybe you can try running a port forward in a separate container deployed in the same pod as your Spring app.

-- Burak Serdar
Source: StackOverflow