Redis Connection Refused Mac

Info: Docker version ($ docker -version): 18.09.2, build 6247962 System info (Mac, PC, Linux): Mac System info disto/version: Mojave Issue: I have set a password for redis by uncomment in redis Dockerfile ## For security settings uncomm. Connection refused. This problem is caused by not installing the Redis server. Redis is a very popular data store used across all kinds of web apps it’s supported natively by Mac and Linux operating systems. Heck, you can even use Docker to run Redis. The purpose of this guide is to setup Redis so we can use in our Python applications including Django, Flask, Fastapi, Celery, and pure python apps. The thing is that redis-server is binded to listed by default on localhost. So, find redis.conf and find then bind setting (bind 127.0.0.1 - its something like this). Replace the ip address with the private ip address of the VM where redis is running. Then, restart the redis server. This issue can be marked as resolved. Replaced bind 127.0.0.1 with bind 0.0.0.0 in the /etc/redis/redis.conf file, the line does not have a leading # nor space, Replaced protected-mode yes with protected-mode no in this same file, Allowed all traffic to port 6379 using ufw allow 6379 and ufw allow 6379/tcp; But I can’t get it to work.

You’ve heard that Redis has an embedded scripting language, but haven’t given ita try yet? Here’s a tour of what you need to understand to use thepower of Lua with your Redis server.

Hello, Lua!

Our first Redis Lua script just returns a value without actually interacting withRedis in any meaningful way:

This is as simple as it gets. The first line sets up a local variable with ourmessage, and the second line returns that value from the Redis server to theclient. Save this file locally as hello.lua and run it like so:

Connectivity Problems?

This redis-cli example assumes that you're running a Redisserver locally. If you're working with a remote server like RedisGreen, you'llneed to specify host and port information. Find the Connect button onyour RedisGreen dashboard to quickly copy the login info for your server.

See also: Could not connectto Redis at 127.0.0.1:6379: Connection refused.

Running this will print “Hello, world!”. The first argument ofEVAL is the complete lua script — here we’re using the catcommand to read the script from a file. The second argument is the number of Rediskeys that the script will access. Our simple “Hello World” script doesn’taccess any keys, so we use 0.

Accessing Keys and Arguments

Suppose we’re building a URL-shortener. Each time a URL comes in we want to storeit and return a unique number that can be usedto access the URL later.

We’ll use a Lua script to get a unique ID from Redis using INCR andimmediately store the URL in a hash that is keyed by the unique ID:

We’re accessing Redis for the first time here, using the call() function.call()’s arguments are the commands to send to Redis: first we INCR <key>,then we HSET <key> <field> <value>. These two commands will run sequentially— Redis won’t do anything else while this script executes, and it will runextremely quickly.

We’re accessing two Lua tables, KEYS and ARGV. Tables are associativearrays, and Lua’s only mechanism for structuring data. For ourpurposes you can think of them as the equivalent of an array in whateverlanguage you’re most comfortable with, but note these two Lua-isms that trip upfolks new to the language:

Client
  • Tables are one-based, that is, indexing starts at 1. So the first element inmytable is mytable[1], the second is mytable[2], etc.

  • Tables cannot hold nil values. If an operation would yield a table of [ 1,nil, 3, 4 ], the result will instead be [ 1 ] — the table istruncated at the first nil value.

When we invoke this script, we need to also pass along the values for the KEYSand ARGV tables. In the raw Redis protocol, the command looks like this:

When calling EVAL, after the script we provide 2 as the number ofKEYS that will be accessed, then we list our KEYS, and finally we providevalues for ARGV.

Normally when we build apps with Redis Lua scripts, the Redisclient library will take care of specifying the number of keys. The above codeblock is shown for completeness, but here’s the easier way to do this on at thecommand line:

When using --eval as above, the comma separates KEYS[] from ARGV[] items.

Just to make things clear, here’s our original script again, this time withKEYS and ARGV expanded:

When writing Lua scripts for Redis, every key that isaccessed should be accessed only by the KEYS table. The ARGV table is used for parameter-passing — here it’s the value ofthe URL we want to store.

Conditional Logic: increx and hincrex

Our example above saves the link for our URL-shortener, but we also need totrack the number of times a URL has been accessed. To do that we’ll keep acounter in a hash in Redis. When a user comes along with a link identifier,we’ll check to see if it exists, and increment our counter for it if it does:

Each time someone clicks on a shortlink, we run this script to track that thelink was shared again. We invoke the script using EVAL and pass inlinks:visits for our single key and the link identifier returned from ourprevious script as the single argument.

The script would look almost the same without hashes. Here’s ascript which increments a standard Redis key only if it exists:

SCRIPT LOAD and EVALSHA

Redis connection refused mac high sierra

Remember that when Redis is running a Lua script, it will not run anything else.The best scripts simply extend the existing Redis vocabulary of small atomic dataoperations with the smallest bit of logic necessary. Bugs in Lua scripts can lockup a Redis server altogether — best to keep things short and easy to debug.

Even though they’re usually quite short, we need not specify the full Lua scripteach time we want to run one. In a real application you’ll instead register eachof your Lua scripts with Redis when your application boots (or when you deploy),then call the scripts later by their unique SHA-1 identifier.

An explicit call to SCRIPT LOAD is usually unnecessary in a live applicationsince EVAL implicitly loads the script that is passed to it. An applicationcan attempt to EVALSHA optimistically and fall back to EVAL only if the scriptis not found.

If you’re a Ruby programmer, take a look at Shopify’s Wolverine,which simplifies the loading and storing of Lua scripts for Ruby apps. For PHPprogrammers, Predis supports adding Luascripts to be called just as though they were normal Redis commands. If youuse these or other tools to standardize your interaction with Lua, let me know— I’d be interested to find out what else is out there.

When to use Lua?

Redis support for Lua overlaps somewhat with WATCH/MULTI/EXECblocks, which group operations so they are executed together. So how do youchoose to use one over the other? Each operation in a MULTI block needs to beindependent, but with Lua, later operations candepend on the results of earlier operations. Using Lua scripts can also avoidrace conditions that can starve slow clients when WATCH is used.

From what we’ve seen at RedisGreen, most apps that use Lua will also useMULTI/EXEC, but not vice versa. Most successful Lua scripts are tiny, and justimplement a single feature that your app needs but isn’t a part of the Redisvocabulary.

Visiting the Library

The Redis Lua interpreter loads seven libraries: base, table,string,math,debug,cjson,and cmsgpack. The firstseveral are standard libraries that allow you to do the basic operations you’dexpect from any language. The last two let Redis understand JSON and MessagePack— this is an extremely useful feature, and I keep wondering why I don’tsee it used more often.

Web apps with public APIs tend to have JSON lying around all over. So maybe youhave a bunch of JSON blobs stored in normal Redis keys and you want to accesssome particular values inside of them, as though you had stored them as a hash.With Redis JSON support, that’s easy:

Here we check to see if the key exists and quickly return nil if not. Then weget the JSON value out of Redis, parse it with cjson.decode(), and return therequested value.

Loading this script into your Redis server lets you treat JSON values stored inRedis as though they were hashes. If your objects are reasonably small, this isactually quite fast, even though we have to parse the value on each access.

If you’re working on an internal API for a system that demands performance,you’re likely to choose MessagePack over JSON, as it’s smaller and faster.Luckily with Redis (as in most places), MessagePack is pretty much a drop-inreplacement for JSON:

Crunching Numbers

Lua and Redis have different type systems, so it’s important to understandhow values may change when crossing the Redis-Lua border. When a number comes fromLua back to a Redis client, it becomes aninteger — any digits past the decimal point are dropped:

When you run this script, Redis will return an integer of 3 — you lose theinteresting pieces of pi. Seems simple enough, but things get a bit more trickywhen you start interacting with Redis in the middle of the script. An example:

The resulting value here is astring: '3.2' Why? Redis doesn’t have a dedicated numeric type. When we first SET the value, Redis saves it as a string, losing all record of the fact that Lua initially thought of the value as a float. When we pull the value out later, it’s still a string.

Values in Redis that are accessed with GET/SET should be thought of as strings exceptwhen numeric operations like INCR and DECR are run against them. Thesespecial numeric operations will actually return integer replies (andmanipulate the stored value according to mathematical rules), but the“type” of the value stored in Redis is still a string value.

Gotchas: A Summary

These are the most common errors that we see when working with Lua in Redis:

  • Tables are one-based in Lua, unlike most popular languages. Thefirst element in the KEYS table is KEYS[1], the second is KEYS[2],etc.

  • A nil value terminates a table in Lua. So [ 1, 2, nil, 3 ] willautomatically become [1, 2]. Don’t use nil values in tables.

  • redis.call will raise exception-style Lua errors, whileredis.pcall will automatically trap any errors and return them astables that can be inspected.

  • Lua numbers are converted to integers when being sent to Redis — everythingpast the decimal point is lost. Convert any floating point numbers to stringsbefore returning them.

  • Be sure to specify all the keys you use in your Lua scripts in the KEYStable, otherwise your scripts will probably break in future versions ofRedis.

  • Lua scripts are just like any other operation in Redis: nothing else runswhile they’re being executed. Think ofscripts as a way to expand the vocabulary of the Redis server — keep themshort and to-the-point.

Further Reading

There are lots of great resources for Lua and Redis online — here are a few Iuse:

I probably spend more time than most in redis-cli, because I find it invaluable when I’m writing software or getting to know a new module. If I didn’t have redis-cli, understanding Redis’ data structures and testing connections would be far more complicated, and I probably would’ve stopped using Redis long ago.

Redis-cli by itself isn’t that complicated – it’s a REPL (read–eval–print loop) that speaks to the Redis server. However, getting this jewel of a tool is not straightforward for many. The source for redis-cli is included in the Redis github repository and is automatically compiled when you build Redis from source. But what happens if you can’t (or don’t want to) build Redis from source? It means you also don’t have redis-cli and building an entire database from source just to get access to the command-line interface (CLI) utility is overkill and sometimes not even an option.

In this post, I’ll share how to get redis-cli without installing or having to make a full Redis server, but first let’s look at a couple scenarios.

Problem: Can’t built Redis from source

For those of us on Linux or macOS, building Redis from source involves having the relevant compilers and tools on your system and running make, which produces both the CLI and the Redis server. For most developers on these platforms, that’s not a huge burden.

However, if you’re not on a unix-like system, things get complicated quickly. For various reasons, you can’t just compile Redis on Windows. Microsoft once supported a fork of Redis that ran directly on Windows-based machines, but it’s no longer maintained. That means that, on Windows, you can’t get a current version of redis-cli. While it’s possible to use the Windows Subsystem for Linux that can run Redis, this has its own challenges, such as file system limitations and just generally not feeling native or appropriate for the system. In addition, there are many developers who have development machines locked down in fun and creative ways to explicitly block this type of operation.

Finally, you might be in a situation where you’re on a low-spec server and you just need to do some quick checks in Redis – getting the dependencies and building the software may not be possible in these constrained environments.

Problem: Don’t want to build Redis from source

There are many situations where you may be building software that uses Redis, but you’ll never personally manage or administer even a localhost process of Redis. Imagine if you’re using Redis Enterprise Cloud – you can have a Redis instance in seconds, but if you want to do anything with it you need to have CLI, which requires building the whole package from source. Or perhaps you’re at a large organization that is running a self-managed Redis Enterprise Software cluster. Here too, you may not have an actual need to build the Redis server on your development machine, since you just want to connect up remotely.

Finally, you might want to get up and running quickly. Pulling down the entire Redis C project (and all the tools needed to build that) might not be efficient for your workflow.

If you fall in one of the above scenarios, read on.

Invoking Atwood’s Law

In 2007, Jeff Atwood wrote, rather disparagingly:

“Any application that can be written in JavaScript will eventually be written in JavaScript.”

Bringing this to Redis, Lu Jiajing started a small project (less than 250 lines of JavaScript!) in 2015 to reimplement the overall operation of redis-cli in Node.js. Since then, it’s gotten closer to mimicking the Antirez-provided redis-cli. While not perfect (yet), it provides the bulk of the functionalities that you’d need on a day-to-day basis.

You may ask, why bother with this if you still have to install Node.js first? Well, first off, Node.js provides a much wider range of installation options than Redis. You can get it as a GUI msi for Windows or a pkg for macOS, as well as plain old compressed binaries for Windows, macOS or Linux, and you can also install Node.js via a package manager on many platforms.

Installing and running Node.js redis-cli

Once you’ve installed Node.js and npm, it’s a simple one-liner to get and install the Node.js version of redis-cli:

npm install -g redis-cli

Then you can run it with the command:

rdcli -h your.redis.host -a yourredispassword -p 11111

(using your relevant connection information).

Alternately, if you don’t like global installs, you can clone the repository and install the dependencies:

git clonehttps://github.com/lujiajing1126/redis-cli

cd redis-cli

npm install

Then you can run it from this directory by invoking the index.js file directly with the command line arguments:

node index.js -h your.redis.host -a yourredispassword -p 11111

(using your relevant connection information).

Redis-cli without building Redis

There you have it. You can get redis-cli up and running on your development machine quickly and easily with Node.js redis-cli written by Lu Jiajing. Instead of building the whole Redis project with C, you can just grab Node.js (even better if you already have it installed, and you probably do, let’s be honest), install this small module and start hacking away in Redis.

Bonus

One cool little use of this module is to make it a part of devDependencies in your package.json on a Node.js project. This way, you can effectively “pack-in” redis-cli with your project, making sure everyone on your team has the tool. To do this, install it as a development dependency:

npm install –save-dev redis-cli

Then in your package.json, add the following line to the beginning of the scripts object:

“rediscli”: “node ./node_modules/redis-cli/index.js”,

Now, anyone who has your project can start redis-cli by running:

Redis Connection Refused Mac Download

npm start rediscli -h your.redis.host -a yourredispassword -p 11111

(using your relevant connection information).

Redis Connection Refused Mac Catalina

You can even hard code in arguments if need be, but never include your Redis password in your package.json file!