<p>I am developing an application (car-app) which uses socket.io. and now I am going to deploy it to kubernetes cluster. Then I use Redis pub/sub function to communicate.</p>
<pre><code>My app structure:
  Backend: NodeJS
  Frontend: ReactJS
  Mongodb
</code></pre>
<p>Then I am trying to connect Redis in NodeJS. It can be run on my localhost, but it cannot run on my GKE cluster.</p>
<pre><code>(NodeJS)
const redis = require('redis');
const REDISPORT = 6379;
const subscriber = redis.createClient(REDISPORT, redis);
</code></pre>
<p>Error while running on GKE cluster:</p>
<blockquote>
<p>Error: Redis connection to 127.0.0.1:6379 failed - connect
ECONNREFUSED 127.0.0.1:6379</p>
</blockquote>
<p>I think this maybe caused by service connection and my redis deployment and service are configured below.</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: car-redis-deployment
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: car-redis
    spec:
      containers:
        - name: car-redis
          image: redis:latest
          ports:
            - containerPort: 6379
              name: http-port
  selector:
    matchLabels:
      app: car-redis
</code></pre>
<hr />
<pre><code>apiVersion: v1
kind: Service
metadata:
  name: car-redis-service
spec:
  ports:
    - port: 6379
      protocol: TCP
      targetPort: 6379
  selector:
    app: car-redis
  type: NodePort
</code></pre>

potato
<p>It works on localhost because host might be already configured with <code>redis</code> running, so your <code>node</code> is looking for <code>127.0.0.1:6379</code> and it's able to connect to one without any errors.</p>
<p>Coming to k8s, your deployed <code>application</code> is looking for <code>redis</code> within the same container. So, you are getting an error while doing the same.</p>
<p>While coming to GKE or cloud, you need to configure your <code>node</code> application with the particular <code>host ip</code> or <code>url</code> on which your <code>redis</code> application is running. As, I can see you are already running a <code>redis</code> in your k8 cluster, if it is the same cluster as your <code>node</code> application deployment you can directly connect it with the service using something like this</p>
<p><code>&lt;service-name&gt;.&lt;namespace-name&gt;.svc.cluster.local</code> <a href="https://kubernetes.io/docs/tasks/administer-cluster/namespaces/" rel="nofollow noreferrer">How to communicate between ns?</a></p>
<p>From your example, make sure your <code>node</code> app supports <code>redis</code> url instead of just port. And add your configs <code>car-redis-service.default.svc.cluster.local:6379</code> in your <code>node</code> app it should work without any issues.</p>
