Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

Error: connect ECONNREFUSED 127.0.0.1:6379 — why the app cannot reach Redis after deploy

ECONNREFUSED 127.0.0.1:6379, or Error 111 connecting to localhost:6379 in Python, means nothing was listening where the app looked for Redis. After a deploy that is almost always the app's own container: REDIS_URL is not set, is not read, or the client was created without it and fell back to localhost. Pass the URL to the client, attach a Redis the app can reach, and keep redis:// and rediss:// as the provider gives them.

By Livops team, the people who build and run LivopsUpdated

The message depends on the client. A Node app with node-redis or ioredis prints:

Error: connect ECONNREFUSED 127.0.0.1:6379
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1705:16)

ioredis prefixes it with [ioredis] Unhandled error event: when the app has no error listener[7], and repeats it each time it reconnects. redis-py prints:

redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused.

This page explains what the error means, lists the causes from the most common, shows how node-redis, ioredis, redis-py, Django and aiogram take a Redis URL, and says how Redis is attached on Livops.

What does the error mean?

ECONNREFUSED means the target machine actively refused the connection, which usually happens when nothing is running at that address[1]. So the app reached a host, and nothing was listening on port 6379 there.

Read the host in the message first. 127.0.0.1, ::1 or localhost means the client looked for Redis inside the app’s own container: it never got the real address, or never used it. Any other host means it read an address, and that host is wrong, not reachable from where the app runs, or Redis there is not up.

The same error in other words

  • AggregateError [ECONNREFUSED] in Node, with no text after it. Since Node 20, a connection to a host name tries every address it resolves to, and when all of them fail Node reports one AggregateError holding each attempt[2]. localhost often resolves to both ::1 and 127.0.0.1, so a client that falls back to localhost can show this instead. Printed in full, it holds connect ECONNREFUSED 127.0.0.1:6379 and connect ECONNREFUSED ::1:6379.
  • Error 111 connecting to localhost:6379. Connection refused. in Python. redis-py builds the message as Error <number> connecting to <host>:<port>. <reason>.[10], and 111 is ECONNREFUSED on Linux[11]. On a Mac the number is 61.
  • Error Multiple exceptions: [Errno 111] Connect call failed ('127.0.0.1', 6379), [Errno 111] Connect call failed ('::1', 6379, 0, 0) connecting to localhost:6379. from redis.asyncio, when localhost resolves to both addresses and both are refused.

Every client defaults to localhost

node-redis connects to localhost on port 6379 unless it is given a URL or a host[3][4]. ioredis connects to localhost:6379 by default[6][8]. redis-py’s Redis() defaults to host='localhost' and port=6379[9]. So a client created without arguments works on a laptop with Redis installed and fails, with exactly this error, everywhere else.

Causes, most common first

1. The client was created without the URL

const client = createClient()      // node-redis: localhost:6379
const redis = new Redis()          // ioredis: localhost:6379
r = redis.Redis()                  # redis-py: localhost:6379

The same happens when the code does read the variable but under another name (REDIS_HOST when the platform sets REDIS_URL), or reads it with a local fallback such as os.environ.get("REDIS_URL", "redis://localhost:6379"). Pass the platform’s variable, and fail loudly when it is missing:

REDIS_URL = os.environ["REDIS_URL"]   # KeyError names the missing variable

2. REDIS_URL is not set on the server

The Redis was never attached to the project, or the value lives in a .env file that is kept out of the repository and so never reaches the server. Set it in the platform’s variables, or attach a Redis so the platform writes it for you.

3. A config copied from an example

Django’s cache docs show "LOCATION": "redis://127.0.0.1:6379"[14], and many tutorials and docker-compose files hard-code a host the same way. Copied into settings, that address points at the app’s own container after a deploy. Replace it with the variable.

4. A Docker Compose host name used outside Compose

In Docker Compose each service is reachable by its service name, so a web service connects to db at its container port[13]. redis://redis:6379 from a Compose file works only on that Compose network. On a server, use the address the platform gives you. Inside Compose, connect to the container port, not the published host port: service-to-service traffic uses the container port[13].

5. Redis is not running, or the app starts first

If the host is right and Redis is down, restarting, or still starting, the connection is refused the same way. A client that retries covers the start-up race: ioredis reconnects with exponential backoff by default[6], and node-redis has a reconnect strategy too[4]. A node-redis client must have an error listener: without one, an error is thrown and the Node process exits[3].

6. redis:// where the server wants rediss://, or the reverse

redis:// is a plain TCP connection and rediss:// one wrapped in TLS[9]. node-redis turns TLS on for a rediss: URL[5], and ioredis does the same when the URL is passed to the constructor; a rediss:// URL put in ioredis’s host option is not read as TLS[6]. Redis supports TLS from version 6 as an optional feature, on a tls-port that can replace the plain port or run beside it[12].

A scheme mismatch does not by itself cause ECONNREFUSED: when Redis listens on the port, the connection is accepted, and the failure comes later, in the TLS handshake or on the first command. It often shows up next, once the host is fixed. Keep the scheme exactly as the provider writes it.

7. The build connects to Redis

A framework that renders pages or warms a cache during the build opens a Redis connection where there may be no Redis at all. Connect when the app starts or on the first request, not at import time in code the build runs.

The fix, per client

Node: node-redis

import { createClient } from 'redis'

const client = createClient({ url: process.env.REDIS_URL })
client.on('error', (err) => console.error('Redis error', err))
await client.connect()

The URL format is redis[s]://[[username][:password]@][host][:port][/db-number][4].

Node: ioredis

import Redis from 'ioredis'

const redis = new Redis(process.env.REDIS_URL)
redis.on('error', (err) => console.error('Redis error', err))

ioredis takes the connection string as its first constructor argument, with the database number in the path, as in redis://:[email protected]:6380/4[6].

Python: redis-py

import os
import redis

r = redis.Redis.from_url(os.environ["REDIS_URL"])
r.ping()

from_url accepts redis://, rediss:// and unix:// URLs; the database number comes from a db query parameter, the URL path, or the db argument, in that order, and is 0 when none is given[9]. redis.asyncio.Redis.from_url takes the same URL.

Django cache

import os

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": os.environ["REDIS_URL"],
    }
}

LOCATION is the URL of the Redis instance, in a scheme redis-py understands, and redis-py is the binding Django supports natively[14].

aiogram FSM storage

import os
from aiogram.fsm.storage.redis import RedisStorage

storage = RedisStorage.from_url(os.environ["REDIS_URL"])

RedisStorage.from_url creates the storage from a connection URL in the form redis://user:password@host:port/db[15].

How to confirm the fix

Print the host the app will use, without the password:

node -e 'console.log(new URL(process.env.REDIS_URL).host)'
python -c 'import os, urllib.parse; print(urllib.parse.urlsplit(os.environ["REDIS_URL"]).netloc.split("@")[-1])'

If that prints localhost, or fails because the variable is empty, the variable is the problem, not the network. If it prints the right host and the error goes on, Redis at that host is not up or not reachable from where the app runs.

On Livops

  • Attach Redis to the project. Under Databases, add Redis 7. It runs in its own container inside the project environment. Pick the type when you add it: Persistent (the default) keeps every write on disk, and Cache keeps nothing on disk and drops the least recently used keys when memory is full. The type cannot be changed later.
  • The variables are written for you, to every service in the environment, including ones added later: REDIS_URL, plus REDISHOST, REDISPORT and REDISPASSWORD for code that reads the address in parts. The URL has the form redis://:<password>@redis:6379/0: plain redis://, so keep it as it is rather than changing it to rediss://.
  • Variables take effect on the next deploy. After adding Redis or changing a variable, deploy again, or restart the service to apply them now.
  • The build has no database. Open the Redis connection when the app starts or handles a request, not during the build.
  • There is no public port. The host is the internal name redis, reachable only from services in the project. An app hosted elsewhere cannot use it. Your computer reaches it through Connect from your computer on the database page and an SSH tunnel signed by your key.
  • Staging has its own Redis. A new environment gets an empty database of each type production has; no data is copied.
  • Backups. Redis is backed up every night like the other databases, and a restore opens as a new Redis next to the old one.
  • Starting from scratch. The aiogram 3 bot + Redis template creates a Telegram bot with Redis already attached.

If the app connects to Redis when it starts and cannot, the deploy fails as start_failed: the app’s last lines are on the Logs page, and a web app’s previous version keeps running. See The app did not start. The variables are listed in Databases and Variables. A database is free at 500 MB, one per team; 1 GB is 9 credits a month.

The same error with PostgreSQL, MySQL or MongoDB: ECONNREFUSED: the app cannot reach its database.

Questions

What does ECONNREFUSED 127.0.0.1:6379 mean?

The app tried to open a connection to Redis on its own machine, port 6379, and nothing was listening there. After a deploy the app runs in its own container, so 127.0.0.1 is that container, not the Redis server. The client almost always got no address and used its default, localhost:6379.

Why does Redis work on my machine and not after deploy?

On your laptop Redis runs on the same computer, so localhost reaches it. On the server Redis is a separate service with its own host name, and the app has to be given that address, usually in REDIS_URL. A client created with no URL keeps trying localhost.

What is Error 111 connecting to localhost:6379 in Python?

It is redis-py's form of the same failure. 111 is the Linux number for ECONNREFUSED, so the message says the connection to localhost on port 6379 was refused. On a Mac the same error says 61. Pass REDIS_URL to Redis.from_url instead of creating the client with its defaults.

Should I use redis:// or rediss://?

Use what the Redis provider gives you. rediss:// wraps the connection in TLS and redis:// does not, and a Redis server listens for TLS only when it is set up to. Changing one into the other does not fix ECONNREFUSED, which happens before any TLS starts.

Why does my Node app print AggregateError [ECONNREFUSED] instead?

Since Node 20 a connection to a host name that resolves to several addresses tries each of them. localhost often resolves to both ::1 and 127.0.0.1, and when both are refused Node reports one AggregateError that holds the two ECONNREFUSED errors. The cause and the fix are the same.

Can an app hosted elsewhere use a Livops Redis?

No. A Livops database, Redis included, has no public port and is reachable only from services in its own project, and from your computer through an SSH tunnel. Run the app on Livops too, or use a Redis with a public address.

Sources

  1. Node.js docs — Errors, common system errors (nodejs.org). Checked .
  2. Node.js docs — net, socket.connect() autoSelectFamily (nodejs.org). Checked .
  3. node-redis [email protected] — README (github.com). Checked .
  4. node-redis [email protected] — Client configuration (github.com). Checked .
  5. node-redis [email protected] source — packages/client/lib/client/index.ts (github.com). Checked .
  6. ioredis v6.1.1 — README (github.com). Checked .
  7. ioredis v6.1.1 source — lib/Redis.ts (github.com). Checked .
  8. ioredis v6.1.1 source — lib/redis/RedisOptions.ts (github.com). Checked .
  9. redis-py — Connecting to Redis (redis.readthedocs.io). Checked .
  10. redis-py v8.2.0 source — redis/utils.py (github.com). Checked .
  11. Linux v6.12 source — include/uapi/asm-generic/errno.h (github.com). Checked .
  12. Redis docs — TLS (redis.io). Checked .
  13. Docker docs — Networking in Compose (docs.docker.com). Checked .
  14. Django docs — Django's cache framework (docs.djangoproject.com). Checked .
  15. aiogram docs — Storages (docs.aiogram.dev). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy with Redis

Got a question? — @livops_uz