Back to roadmaps docker-compose Course

Project: Node.js API with Redis Cache Stack

In this project, we will orchestrate a two-service stack: a Node.js Express API server and a Redis cache. The API will read and write data to Redis using the container service name as the hostname.


1. Project Structure

node-redis-stack/
  api/
    index.js
    package.json
    Dockerfile
  docker-compose.yml

2. Building the API Service

Create api/index.js:

// api/index.js
const express = require('express');
const redis = require('redis');

const app = express();
const port = 3000;

// Connect to Redis using the Docker Compose service name as hostname
const client = redis.createClient({ url: 'redis://cache-server:6379' });

client.on('error', (err) => console.error('Redis connection error:', err));
client.connect();

app.get('/visits', async (req, res) => {
  const visits = await client.incr('page_visits');
  res.json({ totalVisits: visits });
});

app.listen(port, () => console.log(`API running on port ${port}`));

Create api/Dockerfile:

FROM node:20-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]

3. Docker Compose Configuration

Create docker-compose.yml in the root directory:

services:
  api-server:
    build: ./api
    container_name: node-api
    ports:
      - "3000:3000"
    depends_on:
      - cache-server

  cache-server:
    image: redis:7-alpine
    container_name: cache-redis

networks:
  default:
    name: app-network

4. Running the Stack

Start all services with a single command:

docker compose up -d --build

Test the API by visiting http://localhost:3000/visits in your browser. Each page refresh increments the Redis visit counter returned by the API.

Published on Last updated: