KAHIBARO
Discord Login Register

21.13. Redis with Docker

Why Use Redis with Docker?

Running Redis with Docker is one of the easiest ways to get a consistent, isolated Redis instance for development and even for production. Docker gives you:

In this chapter you will see practical examples of how to run Redis in Docker and connect it to a backend application.

Running Redis in a Single Container

The simplest way to run Redis in Docker is with a single container.

Pulling the Redis Image

First, get the official Redis image from Docker Hub:

bash
docker pull redis:7

You can also use redis:latest, but using a specific version is more predictable.

Important rule
Always use explicit versions in production, for example redis:7.2, not just latest. This avoids unexpected upgrades when images are rebuilt.

Starting a Redis Container

Run Redis in the foreground:

bash
docker run --name my-redis redis:7

This starts Redis, but you cannot access it from your host by default because no ports are published.

Expose Redis on the default port 6379:

bash
docker run \
  --name my-redis \
  -p 6379:6379 \
  redis:7

Explanation of key flags:

FlagMeaning
--name my-redisSet a readable container name
-p 6379:6379Map host port 6379 to container port 6379
redis:7Use image redis with tag 7

Now you can connect from your host:

bash
redis-cli -h 127.0.0.1 -p 6379 ping
# PONG

If redis-cli is not installed on your host, you can use the one inside the container:

bash
docker exec -it my-redis redis-cli ping
# PONG

Running Redis in the Background

To avoid blocking your terminal, run the container in detached mode:

bash
docker run -d \
  --name my-redis \
  -p 6379:6379 \
  redis:7

Check if it is running:

bash
docker ps

Stop and remove when you are done:

bash
docker stop my-redis
docker rm my-redis

Persisting Redis Data with Volumes

By default, Redis data is stored inside the container filesystem. If the container is removed, the data is lost.

For development this might be fine, but for anything more serious you need persistence.

Using an Anonymous Volume

Quick way to keep data even when recreating the container:

bash
docker run -d \
  --name my-redis \
  -p 6379:6379 \
  -v /data \
  redis:7

Docker will create an anonymous volume attached to /data in the container. Redis uses /data for persistence by default.

However, anonymous volumes are not easy to manage explicitly. A better approach is to use named or bind volumes.

Using a Named Volume

Create a named volume:

bash
docker volume create redis-data

Run Redis with the named volume:

bash
docker run -d \
  --name my-redis \
  -p 6379:6379 \
  -v redis-data:/data \
  redis:7

Now:

Remove the container and recreate:

bash
docker stop my-redis
docker rm my-redis
docker run -d \
  --name my-redis \
  -p 6379:6379 \
  -v redis-data:/data \
  redis:7

Your data is still there.

Using a Bind Mount

If you want to see files on your host, use a bind mount:

bash
mkdir -p ./redis-data
docker run -d \
  --name my-redis \
  -p 6379:6379 \
  -v $(pwd)/redis-data:/data \
  redis:7

Now all Redis data is visible in the ./redis-data folder.

Important rule
Never put your production Redis data on a local, temporary, or non-backed-up directory. For production use a persistent, reliable storage location and proper backup strategy.

Configuring Redis in a Container

The default Redis configuration is fine for local experiments. For real applications you often need to customize it.

You can configure Redis with:

  1. Command line arguments
  2. A custom redis.conf file

Using Command Line Arguments

Example, disable protected mode so Redis is reachable from other machines (only for controlled environments):

bash
docker run -d \
  --name my-redis \
  -p 6379:6379 \
  redis:7 \
  redis-server --appendonly yes --protected-mode no

Here:

Using a redis.conf File

  1. Create a config file, for example redis.conf:
conf
bind 0.0.0.0
port 6379
appendonly yes
maxmemory 256mb
maxmemory-policy allkeys-lru
  1. Run Redis using this config:
bash
docker run -d \
  --name my-redis \
  -p 6379:6379 \
  -v $(pwd)/redis.conf:/usr/local/etc/redis/redis.conf \
  redis:7 \
  redis-server /usr/local/etc/redis/redis.conf

Now Redis uses your custom settings.

Security rule
Never expose a Redis instance on the public internet without:

  • A firewall or private network
  • Proper authentication and access controls
    An open Redis on the internet is a very common and very serious security problem.

Connecting a Backend Application to Redis in Docker

There are two common situations:

  1. Backend on host, Redis in Docker
  2. Backend in Docker, Redis in Docker (same Docker network)

1. Backend on Host, Redis in Docker

You already saw how to expose Redis on port 6379:

bash
docker run -d \
  --name my-redis \
  -p 6379:6379 \
  redis:7

Your backend configuration would look like:

SettingValue
Host127.0.0.1 or localhost
Port6379
Passwordnone by default

Example in Python (using redis-py):

python
import redis
redis_client = redis.Redis(host="localhost", port=6379, db=0)
redis_client.set("greeting", "hello")
print(redis_client.get("greeting"))

2. Backend in Docker, Redis in Docker

It is better to use a Docker network so containers can resolve each other by name.

Create a network:

bash
docker network create backend-net

Run Redis on that network:

bash
docker run -d \
  --name redis-server \
  --network backend-net \
  redis:7

Run your backend container on the same network:

bash
docker build -t my-backend .
docker run -d \
  --name backend-app \
  --network backend-net \
  -p 8000:8000 \
  -e REDIS_HOST=redis-server \
  my-backend

In your backend code, use redis-server as the host:

python
import os
import redis
redis_host = os.getenv("REDIS_HOST", "localhost")
redis_client = redis.Redis(host=redis_host, port=6379, db=0)

Because both containers share backend-net, the backend can find Redis by container name.

Connection rule
When both app and Redis are in the same Docker network, do not use localhost as the Redis host in the app. Use the container name or service name on the network.

Using Redis and FastAPI with Docker Compose

In real projects you often use Docker Compose to manage multi-container setups.

Basic docker-compose.yml Example

Create a file docker-compose.yml:

yaml
version: "3.9"
services:
  redis:
    image: redis:7
    container_name: redis
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data
  backend:
    build: .
    container_name: backend
    ports:
      - "8000:8000"
    environment:
      REDIS_HOST: redis
      REDIS_PORT: 6379
    depends_on:
      - redis
volumes:
  redis-data:

Key points:

Minimal FastAPI + Redis Example

Assume your Dockerfile builds a FastAPI app that uses Redis:

python
# app/main.py
import os
from fastapi import FastAPI
import redis
app = FastAPI()
redis_host = os.getenv("REDIS_HOST", "redis")
redis_port = int(os.getenv("REDIS_PORT", "6379"))
r = redis.Redis(host=redis_host, port=redis_port, db=0)
@app.get("/set/{key}/{value}")
def set_value(key: str, value: str):
    r.set(key, value)
    return {"status": "ok"}
@app.get("/get/{key}")
def get_value(key: str):
    value = r.get(key)
    if value is None:
        return {"key": key, "value": None}
    return {"key": key, "value": value.decode()}

Start everything:

bash
docker compose up

Then test:

bash
curl "http://localhost:8000/set/name/Alice"
curl "http://localhost:8000/get/name"

Using Redis Authentication in Docker

For more secure setups, you can set a Redis password.

Setting a Password via redis.conf

redis.conf:

conf
requirepass my-strong-password
appendonly yes

Run Redis:

bash
docker run -d \
  --name my-secure-redis \
  -p 6379:6379 \
  -v $(pwd)/redis.conf:/usr/local/etc/redis/redis.conf \
  redis:7 \
  redis-server /usr/local/etc/redis/redis.conf

Connect with redis-cli:

bash
redis-cli -h 127.0.0.1 -p 6379
> AUTH my-strong-password
OK
> PING
PONG

Connect from Python:

python
import redis
r = redis.Redis(
    host="localhost",
    port=6379,
    password="my-strong-password",
    db=0,
)

Using AUTH with Docker Compose

Example docker-compose.yml:

yaml
version: "3.9"
services:
  redis:
    image: redis:7
    command: ["redis-server", "--requirepass", "my-strong-password"]
    ports:
      - "6379:6379"
  backend:
    build: .
    environment:
      REDIS_HOST: redis
      REDIS_PORT: 6379
      REDIS_PASSWORD: my-strong-password
    depends_on:
      - redis

In your backend:

python
import os
import redis
redis_client = redis.Redis(
    host=os.getenv("REDIS_HOST", "redis"),
    port=int(os.getenv("REDIS_PORT", "6379")),
    password=os.getenv("REDIS_PASSWORD"),
    db=0,
)

Security rule
Never hardcode real production passwords in docker-compose.yml or images. Use environment variables, Docker secrets, or a dedicated secrets manager.

Common Troubleshooting Tips

Here are typical problems and how to fix them.

Problem: Cannot Connect from Host

Symptoms:

bash
redis-cli -h 127.0.0.1 -p 6379 ping
# could not connect to Redis

Checklist:

CheckCommand / Fix
Container is runningdocker ps
Port is publishedStarted with -p 6379:6379
Port not already in useChange -p 6380:6379 if 6379 is busy
Firewall rulesEnsure firewall allows connections to that port

Problem: App in Container Cannot Reach Redis

Typical error: "Connection refused" when using localhost from inside the app.

Fix:

Example wrong configuration:

python
redis.Redis(host="localhost", port=6379)

Correct for Docker Compose:

python
redis.Redis(host="redis", port=6379)

Problem: Data Is Lost After Container Recreated

You did not use a volume, or you used an anonymous volume that you later removed.

Fix:

Summary

In this chapter you learned how to:

These patterns are the foundation for using Redis in real backend projects, from local development to more advanced environments.

Views: 7

Comments

Please login to add a comment.

Don't have an account? Register now!