Home > OS >  Getting Connection refused while trying to access service from kubernetes pod
Getting Connection refused while trying to access service from kubernetes pod

Time:11-29

I am new to kubernetes and I am trying to learn it by deploying a simple node server using AWS EKS. (kubernetes is alreay setup to talk to the created AWS EKS cluster)

Here is code for my simple node file (server.js)

const express = require('express')
const app = express()
const port = 8080

app.get('/', (req, res) => {
 res.send('Hello World!')
})

app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})

Here is how the Dockerfile looks like:

FROM node:12
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
COPY package*.json ./
RUN npm ci
# Bundle app source
COPY . .
EXPOSE 8080
CMD [ "node", "server.js" ]

I am able to run the above server in my local by creating a docker image.

Now, in order to deploy this server here are the steps that I followed:
First, I pushed the above image to doceker hub (aroraankit7/simple-server) Second, I created a deployment.yaml file which looks like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: simple-server-app
  labels:
    app: simple-server-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: simple-server-app
   template:
     metadata:
       labels:
         app: simple-server-app
     spec:
       containers:
       - name: simple-server
         image: aroraankit7/simple-server:v1
         ports:
         - containerPort: 8080

Third, I deployed this using kubectl apply command. Here is the output for kubectl get pods enter image description here

Then, I created the service.yaml file. Here is how it looks:

apiVersion: v1
kind: Service
metadata:
name: simple-server-svc
labels:
  run: simple-server
spec:
  ports:
  - port: 8080
    targetPort: 8080
    protocol: TCP
  selector:
    run: simple-server

I then deployed this using the kubectl apply command. Output for kubectl describe services: enter image description here

Next, I logged into on of my pods by using the command: kubectl -it exec simple-server-app-758dfb88f4-4cfmp bash

While inside this pod, I ran the following the command: curl http://simple-server-svc:8080 and this was the output that I got: curl: (7) Failed to connect to simple-server-svc port 8080: Connection refused

Why is the connection getting refused?

When I am running curl http:localhost://8080, I am getting the right output (Hello World! in this case)

CodePudding user response:

Your service is not bound to the deployment. You need to modify the selector in your service.yaml to the following:

apiVersion: v1
kind: Service
metadata:
 name: simple-server-svc
 labels:
  run: simple-server
spec:
  ports:
  - port: 8080
    targetPort: 8080
    protocol: TCP
  selector:
    app: simple-server-app

You can use kubectl expose command to avoid mistakes like this.

  • Related