Skip to content

Node.js and Redis with Docker Compose

How I describe a two-container app of Node.js and Redis with Docker Compose in projects: one YAML file for the whole stack, service discovery via the service name, persistence through a volume – and why depends_on doesn’t wait for readiness.

≈ 13 min readSoftwarePlatform

A second container doesn’t double the work, it changes it. A single docker run is about one image, one port, maybe two environment variables. As soon as a Node process depends on Redis, new questions come up that you can only answer with tedious command-line acrobatics: Which network are both containers in? At which address does one find the other? Who starts first – and where does the data go when a container gets replaced?

Docker Compose answers these questions in a single place. Afterwards, the knowledge of how the stack starts lives in a versioned file instead of in people’s heads and a setup doc: git clone, docker-compose up, running. A new team member no longer loses half a day to Node versions, a local Redis installation and occupied ports. You pay for it with a file that needs maintenance – a deal that pays off quickly.

I walk the technical path completely: from the docker-compose.yml through service discovery and persistence to the pitfall that easily costs half an hour the first time. The state is summer 2018, so Compose file v3 and the hyphenated CLI docker-compose.

Editorial note (July 2026): Current Docker Compose can wait for a successful health check with the long form of depends_on and condition: service_healthy. The application should still cope with dropped connections and restarts on its own; a health check doesn’t replace a retry strategy. The main text keeps the limitation of the Compose v3 format of the time.

Why Compose at all#

A single container is quickly explained. But as soon as two containers have to work together, the imperative variant gets tedious: create a network, start both containers in it, publish ports, set environment variables, mind the start order. That is a lot of commands nobody reproduces from memory without mistakes – least of all the colleague who clones the project tomorrow for the first time.

Compose turns this around. Instead of a sequence of commands, I write a declarative description of the target state. The file says which services exist, which images they use, which ports are open and how they relate. The start command is always the same afterwards. If you have worked with Docker before, you know the principle from the Dockerfile – Compose just lifts it one level higher, from one image to a whole application.

The whole thing follows a simple idea: reproducible, encapsulated environments that start the same way on every machine.

The docker-compose.yml#

Here is the file I start with. Two services, kept minimal so that every line has a recognizable job.

version: '3'
services:
  web:
    build: .
    environment:
      NODE_ENV: production
      REDIS_HOST: 'redis'
      REDIS_PORT: '6379'
    ports:
      - '8080:8080'
    depends_on:
      - 'redis'
  redis:
    image: redis:4.0.11

The first line is mandatory in 2018: version: '3'. Without this key, Compose refuses to read the file. Below it come the top-level keys that interest us here – services: for sure, volumes: and networks: in a moment.

Two lines are worth a closer look. The web service has build: . – Compose builds the image locally from the Dockerfile in the current directory. The redis service has image: redis:4.0.11 – here a ready-made image is pulled from the registry. That is the central contrast:

  • I use build: for my own code, which doesn’t exist as a finished image yet. Compose runs a docker build in the background.
  • I use image: for everything I take over unchanged – databases, caches, message brokers. I pin Redis to a concrete version (4.0.11) instead of latest so the environment stays reproducible.

In case my web service has already been built and pushed to a registry, I simply swap build: . for image: mikebild/compose-nodejs-redis:1.0.0. The same file, a different source – exactly what you want in a deploy context.

What’s missing from the redis service is also striking: no ports. That is intentional. Only web publishes a port to the host with '8080:8080', because only the web service should be reachable from outside. Redis stays internal to the containers and therefore doesn’t need to be published on the host. I’ll come back to this isolation point below, because it has a very real security side.

Service discovery: Redis is simply called “redis”#

That leaves the question of how the Node process knows at which address to find Redis. There is no IP written anywhere, after all.

On startup, Compose automatically creates a default network named after the project, something like <projekt>_default. Every service is attached to this network and reachable in it under its service name via built-in DNS. In other words: every service reaches every other service under that service’s name. The name redis from the YAML becomes the hostname in the network.

That is why I set REDIS_HOST: 'redis' in the file. The Node client connects to redis:6379 – no hardcoded IP, no --link acrobatics. If Compose gives the container a different internal address tomorrow, it doesn’t matter, because resolution happens via the name.

graph LR
  Client["Client / Browser"] -->|"Host port 8080"| Web
  subgraph net["Compose default network"]
    Web["web container"] -->|"DNS: redis:6379"| Redis["redis container"]
  end
  Redis --> Vol[("volume<br/>redis-data (/data)")]

From outside, exactly one way leads in, via the published host port 8080 to web. Internally, web talks to redis via the service name. And the Redis data lives in a volume, which we’ll get to in a moment.

If you want to make the default network visible, you can also write it out explicitly. I like to do that once in a new project to make it clear there is no magic involved:

version: '3'
services:
  web:
    build: .
    environment:
      REDIS_HOST: 'redis'
      REDIS_PORT: '6379'
    ports:
      - '8080:8080'
    networks:
      - app-net
    depends_on:
      - 'redis'
  redis:
    image: redis:4.0.11
    networks:
      - app-net
networks:
  app-net:

Functionally, this changes nothing compared to the first file – Compose would have built a network anyway. But the mechanism is now visible in the file, and the network is no longer an implicit side effect.

The Node client#

So the connection doesn’t stay abstract, here is the relevant excerpt of the server. It is a lean Express server that uses node_redis in version ^2.8, common in 2018 – so the callback API, not yet the later promises.

const SERVICE_PORT = process.env.SERVICE_PORT || 8080;
const REDIS_HOST = process.env.REDIS_HOST || 'localhost';
const REDIS_PORT = process.env.REDIS_PORT || '6379';

const express = require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient(REDIS_PORT, REDIS_HOST);

client.on('error', err => {
  console.error(`Redis connection error.\n${err.message}`);
  process.exit(1);
});

app.get('/redis', (req, res, next) => {
  client.get('foo', (error, result) => {
    if (error) return next(error);
    res.send(result);
  });
});

app.post('/redis', (req, res, next) => {
  client.set('foo', 'bar', (error, result) => {
    if (error) return next(error);
    res.status(201).send('done');
  });
});

app.listen(SERVICE_PORT, () => console.log(`Listen on ${SERVICE_PORT}`));

The crucial line is redis.createClient(REDIS_PORT, REDIS_HOST). Host and port come from the environment, and Compose fills the environment through the environment block. That keeps the code free of addresses. On my laptop it runs against localhost, in the Compose network against redis – without a single line of application code changing.

There is one detail I keep in mind: the client.on('error', …) handler terminates the process with process.exit(1) as soon as the Redis connection fails. That is deliberately harsh and leads straight to the most important pitfall.

The pitfall: depends_on doesn’t wait for “ready”#

depends_on: ['redis'] reads as if Compose waits until Redis is ready before starting web. It doesn’t. depends_on only controls the start order: Compose starts the Redis container before the web container. But it doesn’t wait until Redis accepts connections – only until the container has been started.

The difference sounds academic until the harsh error handler above strikes. Redis needs a moment until the server inside the container is actually listening. If web starts in this window and tries to connect immediately, client.on('error') fires, the process exits with exit code 1 – and the freshly started stack is already half dead again. On slower machines, this happens reproducibly.

The clean solution isn’t in the YAML but in the application. It has to tolerate dropped connections and attempt a reconnect with retry instead of bailing out on the first error. Where I don’t want to touch the application code, in 2018 I put a small wait script in front of the start – wait-for-it.sh, dockerize or wait-for checks whether redis:6379 is reachable before the Node process starts.

One thing needs an explicit no here: the long form depends_on: {redis: {condition: service_healthy}}, which waits for a health check, doesn’t exist in Compose v3 in 2018. If you write it into a v3 file, it simply isn’t recognized. So the wait logic belongs in the application or a wait script, period.

Persistence: Redis needs a volume#

The second pitfall is quieter, but more annoying. In the starting file, Redis has no volume. As long as the container runs, all is well – the data lives in the container file system under /data. But as soon as the container gets replaced, for example after docker-compose down and another up, the cache is empty. The container is ephemeral, and so is its file system.

If you use Redis as more than a throwaway cache, mount a named volume on /data. The redis image stores its RDB snapshots exactly there.

version: '3'
services:
  web:
    build: .
    environment:
      REDIS_HOST: 'redis'
      REDIS_PORT: '6379'
    ports:
      - '8080:8080'
    depends_on:
      - 'redis'
  redis:
    image: redis:4.0.11
    volumes:
      - 'redis-data:/data'
volumes:
  redis-data:

The named volume redis-data survives the container’s lifecycle. I can rebuild web, shut the stack down and bring it back up – the Redis data is still there. Only an explicit docker-compose down -v also cleans up the volumes.

With that, I have the four building blocks that make up a Compose file:

  • services are the application’s containers, here web and redis.
  • ports defines which container ports are published to the host; only web gets one.
  • volumes keeps data in named volumes that should survive the container, here redis-data.
  • networks describes the mostly automatic network that enables service discovery by service name.

The cycle: up, logs, down#

In operation, it’s only a handful of commands, and they stay the same across projects. I start the stack in the background, look at the logs and shut everything down again at the end.

docker-compose up -d
docker-compose logs web

curl -X POST http://localhost:8080/redis
curl http://localhost:8080/redis

docker-compose down

up -d starts both containers detached. logs web shows the web service’s output specifically, which helps when debugging the startup window above. The two curl calls first write the value to Redis and then read it back – proof that web actually reaches its neighbor under the name redis. down stops and removes the containers and the default network; the named volumes stay unless I add -v.

By the way, if you use Docker Toolbox instead of Docker for Mac or Windows, you don’t reach the stack at localhost but at the IP of the docker-machine, 192.168.99.100 in the default configuration. In 2018 that is still reality on many machines and costs a few puzzled minutes the first time.

The real gain: time to the first commit#

The YAML is only the means. The result is an environment that everyone on the team gets with the same two commands. Whoever joins the project today clones the repository, types docker-compose up and shortly after has a running stack of Node and Redis in front of them – without hunting for the right Node version by hand, without installing Redis locally, without the silent assumption that port 6379 is free. The environment lives in the file, not on a wiki page nobody maintains.

This is where Compose pays off in business terms. Onboarding is expensive, and the most expensive part is rarely understanding the code – it is setting up an environment in which the code runs at all. Compose moves exactly this part from every single developer into a versioned file. The time to the first commit, which can otherwise be anywhere between half a day and a full day, shrinks to the duration of an image pull.

It isn’t free. I take on an additional abstraction the team has to understand, and a file that needs maintenance. Version pinning is discipline: a redis:latest undermines exactly the reproducibility I use Compose for in the first place. And Compose covers development and local integration, not production operations with their questions of fault tolerance, scaling and secrets.

So the decision falls at a clear boundary. As soon as more than one process works together and more than one person touches the project, Compose quickly earns back its effort – every setup hour avoided per new team member already makes the file worth it. For a single tool without neighbors, docker run remains the more honest answer. What tips the scale is less the technology than the friction it saves.

A word on security#

The missing ports entry for Redis is intentional and the actual core of the isolation. ports publishes on all host interfaces. If I exposed Redis with '6379:6379', an open Redis instance, unsecured by default, would sit on the network – and Redis has repeatedly made negative headlines for exactly that. Inside the Compose network, web reaches its cache via the service name anyway. Nobody should reach it from outside. So I leave Redis unpublished. The principle stays simple: only services that must be reachable from the host get a published port.

As an aside: the links entry you come across in older examples is legacy. In v3, the default network with its DNS makes it unnecessary. If you still have it in place, you can remove it.

Conclusion#

Compose turns a handful of docker run commands into a single, readable file that describes the whole stack. image versus build separates adopted services from self-built ones. Service discovery via the service name gets hardcoded IPs out of the way completely – REDIS_HOST: 'redis' is enough, and the Node client connects to redis:6379. A named volume on /data saves the Redis data across the container lifecycle. And ports publishes only what really needs to be reachable from outside.

The one point that matters most to me: depends_on orders the start but doesn’t guarantee readiness. If you don’t know that, you chase a race condition bug that no YAML line fixes – the wait logic belongs in the application or a small wait script. If you know it, you build the stack to be resilient from the start.

But more important than any single YAML line is what it saves the team. A reproducible environment shortens the loop from cloning to the first commit, takes the friction out of onboarding and turns “works on my machine” into a verifiable statement instead of a hope. As a side effect, that raises quality, because everyone develops and tests against the same state. The boundary stays clear: Compose is a tool for development and local integration, not a production orchestrator. Within that boundary, docker-compose up feels like a single, reliable move every time – and that is exactly the gain.

Further reading#

Revised and translated from German with the help of AI.