Redis from Express
Using Redis from a Node.js Express App via Docker Compose
Updated: 03 September 2023
Setup Project
Init an NPM project with Redis and Express:
Create Container
To start a Redis Container run:
Test A DB Query
The following code should create a key-value pair on redis, you can add this to a file called db.js
db.js
Or, if you’re feeling that the default client is sketchy you can use this with the explicit url:
Either way, you can run this using node db.js
which should output the creation success
View the Data from DB
You can login to the redis container via docker, and then from the command line you can log into the db itself with:
And then list all the keys using:
And we can even get the data from the DB using the get
command:
Create an Express Client
A simple express client which will do key-value creates and lookups can be defined in an index.js
file:
index.js
You can then just run the web server with:
The Dockerfile
for the above app is so:
Test the App
And you should then be able to make requests to the application from something like Postman for creating and retreiving a record
Set
With the server running you can create a new item with:
Get
You can then get the value using the key with:
Setting Up Compose
Before moving on please ensure you stop the Redis container we previously started with
docker container stop node-redis
Since we’re using Docker, it would be great to configure our application using a Docker compose file. In the compose file we’ll define a web
and redis
service and will provide the Redis URL in the environment for our Express app, the service config for web
is:
And for the redis
service it’s pretty much the same as what we provided to the container we started with the command line:
So the overall compose file will now be:
docker-compose.yml
Access Redis from Within Network
Now, it should be possible for us to access the redis instance using Service Discovery within the compose network, to do this we’ll use the REDIS_URL
environment variable we defined above which will make a connection to redis://redis:6379
which will be resolved within the docker network that our application will run in
We can modify our client app by updating the connection to Redis as follows:
index.js
So the final file will now be:
index.js
And you should be able to run this all with:
And this will run Redis as well as your Application, and you are pretty much good to use the application exactly as we did before addding the compose setup and will connect our application to Redis from within the docker network