Docker Compose for Redis and Node: Simple Setup Guide
Use a
docker-compose.yml file to define services for redis and node. Link the Node.js service to Redis by setting the Redis hostname as the service name redis in your Node.js app configuration.Syntax
A docker-compose.yml file defines multiple services that run together. Each service has a name and configuration like the image to use, ports to expose, and environment variables.
For Redis and Node.js, you define two services: redis for the Redis server and node for your Node.js app. The Node.js service can connect to Redis using the service name redis as the hostname.
yaml
version: '3.8' services: redis: image: redis:7.0 ports: - '6379:6379' node: build: ./node-app ports: - '3000:3000' depends_on: - redis
Example
This example shows a docker-compose.yml file that runs Redis and a Node.js app. The Node.js app connects to Redis using the hostname redis. The Node.js app listens on port 3000, and Redis listens on port 6379.
yaml
version: '3.8' services: redis: image: redis:7.0 ports: - '6379:6379' node: build: ./node-app ports: - '3000:3000' depends_on: - redis # node-app/Dockerfile FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . CMD ["node", "index.js"] # node-app/index.js const redis = require('redis'); const client = redis.createClient({ url: 'redis://redis:6379' }); client.connect().then(() => { console.log('Connected to Redis'); client.set('key', 'value'); client.get('key').then(value => { console.log('Value from Redis:', value); }); }); const express = require('express'); const app = express(); app.get('/', (req, res) => res.send('Hello from Node.js with Redis!')); app.listen(3000);
Output
node_1 | Connected to Redis
node_1 | Value from Redis: value
Common Pitfalls
- Not using the Redis service name
redisas the hostname in the Node.js app causes connection errors. - Forgetting to add
depends_onmeans Node.js may start before Redis is ready. - Exposing ports incorrectly can block access; map container ports to host ports properly.
javascript
Wrong: const client = redis.createClient({ url: 'redis://localhost:6379' }); Right: const client = redis.createClient({ url: 'redis://redis:6379' });
Quick Reference
Tips for Docker Compose with Redis and Node.js:
- Use service names as hostnames for inter-service communication.
- Use
depends_onto control startup order. - Map ports to access services from your host machine.
- Build your Node.js app with a Dockerfile for easy deployment.
Key Takeaways
Define Redis and Node.js as separate services in docker-compose.yml.
Use the Redis service name as the hostname in your Node.js Redis client.
Add depends_on to ensure Redis starts before Node.js.
Expose ports to access services from your host machine.
Build your Node.js app with a Dockerfile for consistent environments.