- Open docker terminal
- displays
docker is configured to use the default machine with IP 192.168.99.100
- Start
redis:alpine
prebuilt container from docker hub.
docker run --name redis -p 6379:6379 -d redis:alpine
- the "alpine" image is very slim (5MB!)
- the running container binds the internal port 6379 to the "outside" world port with same number
- the port 6379 is the default Redis port for simplicity
- Open Git repo (for example
~/git/training/node
) - Pick node
nvm use 5
- Create new NPM package
npm init -y
- Install redis Node client
npm install --save redis
- Write small Redis example, like this one
// index.js
var redis = require("redis"),
client = redis.createClient();
client.on("error", function (err) {
console.log(err);
});
client.set("akey", "string val", redis.print);
client.get("akey", redis.print);
- Run the example
node index.js
and get errors!
$ node index.js
Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED
Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED
...
We need to connect to the Redis server running inside the Docker container, not on the host 127.0.0.1
.
The Docker's virtual machine IP is displayed when the docker terminal starts, or you can look it up
using docker-machine ls
command. In our case it is 192.168.99.100
.
- Modify the example to take the Redis host address as a parameter
// index.js
var redis = require("redis"),
client = redis.createClient({
host: process.env.REDIS_HOST || '127.0.0.1'
});
- Start the example again, setting the HOST environment variable first
$ REDIS_HOST=192.168.99.100 node index.js
Reply: OK
Reply: string val
What if there are lots of environment settings to pass? Can we store all environment settings groupped and use bunch of them without accidentally adding them to a public repo (see https://github.com/bahmutov/ban-sensitive-files for example).
I have a tool as-a that allows one to store all groups of private settings that should NOT be checked in a single inside the user's private home folder. In our case, let us install the tool and create the file to keep all our settings
npm install --global as-a
touch ~/.as-a.ini
Create a group with just a single setting for local Docker Redis. I will even add the Docker command as a comment there
; .as-a.ini
; Redis running inside a Docker container
; Start the image as
; docker run --name redis -p 6379:6379 -d redis:alpine
[red-dock]
REDIS_HOST=192.168.99.100
Now run the example without copy / paste or even remembering and showing the actual settings in the console.
$ as-a red-dock node index.js
Reply: OK
Reply: string val
Nice!
- Redis Docker image docs https://hub.docker.com/_/redis/
- If you need more Docker commands, see https://gist.github.com/bahmutov/1003fa86980dda147ff6
- If you need to start services inside the local environment, consider using quickly.