21.13. Redis with Docker
Table of Contents
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:
- A predictable Redis version and configuration
- Easy cleanup and recreation
- Simple networking with your app containers
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:
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:
docker run --name my-redis redis:7This starts Redis, but you cannot access it from your host by default because no ports are published.
Expose Redis on the default port 6379:
docker run \
--name my-redis \
-p 6379:6379 \
redis:7Explanation of key flags:
| Flag | Meaning |
|---|---|
--name my-redis | Set a readable container name |
-p 6379:6379 | Map host port 6379 to container port 6379 |
redis:7 | Use image redis with tag 7 |
Now you can connect from your host:
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:
docker exec -it my-redis redis-cli ping
# PONGRunning Redis in the Background
To avoid blocking your terminal, run the container in detached mode:
docker run -d \
--name my-redis \
-p 6379:6379 \
redis:7Check if it is running:
docker psStop and remove when you are done:
docker stop my-redis
docker rm my-redisPersisting 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:
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:
docker volume create redis-dataRun Redis with the named volume:
docker run -d \
--name my-redis \
-p 6379:6379 \
-v redis-data:/data \
redis:7Now:
- Data is stored in the
redis-datavolume. - You can remove and recreate the container and keep the data.
Remove the container and recreate:
docker stop my-redis
docker rm my-redis
docker run -d \
--name my-redis \
-p 6379:6379 \
-v redis-data:/data \
redis:7Your data is still there.
Using a Bind Mount
If you want to see files on your host, use a bind mount:
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:
- Command line arguments
- A custom
redis.conffile
Using Command Line Arguments
Example, disable protected mode so Redis is reachable from other machines (only for controlled environments):
docker run -d \
--name my-redis \
-p 6379:6379 \
redis:7 \
redis-server --appendonly yes --protected-mode noHere:
redis:7is the imageredis-server ...overrides the default command
Using a redis.conf File
- Create a config file, for example
redis.conf:
bind 0.0.0.0
port 6379
appendonly yes
maxmemory 256mb
maxmemory-policy allkeys-lru- Run Redis using this config:
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.confNow 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:
- Backend on host, Redis in Docker
- 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:
docker run -d \
--name my-redis \
-p 6379:6379 \
redis:7Your backend configuration would look like:
| Setting | Value |
|---|---|
| Host | 127.0.0.1 or localhost |
| Port | 6379 |
| Password | none by default |
Example in Python (using redis-py):
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:
docker network create backend-netRun Redis on that network:
docker run -d \
--name redis-server \
--network backend-net \
redis:7Run your backend container on the same network:
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:
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:
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:
- Both services share a default network created by Compose.
- The backend can use host
redisand port6379. depends_onensures Redis container starts before the backend.
Minimal FastAPI + Redis Example
Assume your Dockerfile builds a FastAPI app that uses Redis:
# 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:
docker compose upThen test:
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:
requirepass my-strong-password
appendonly yesRun Redis:
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:
redis-cli -h 127.0.0.1 -p 6379
> AUTH my-strong-password
OK
> PING
PONGConnect from 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:
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:
- redisIn your backend:
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:
redis-cli -h 127.0.0.1 -p 6379 ping
# could not connect to RedisChecklist:
| Check | Command / Fix |
|---|---|
| Container is running | docker ps |
| Port is published | Started with -p 6379:6379 |
| Port not already in use | Change -p 6380:6379 if 6379 is busy |
| Firewall rules | Ensure 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:
- Use
redis(the service name) as host when using Docker Compose. - Or use the container name when using manual networks.
Example wrong configuration:
redis.Redis(host="localhost", port=6379)Correct for Docker Compose:
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:
- Use a named volume:
-v redis-data:/data - Or a bind mount to a known directory
Summary
In this chapter you learned how to:
- Run Redis in Docker with
docker run - Persist data with named volumes and bind mounts
- Configure Redis with command line arguments or
redis.conf - Connect backend applications to Redis in Docker, both from host and from other containers
- Use Redis and a backend together with Docker Compose
- Add authentication to your Redis container
- Diagnose common connection and persistence problems
These patterns are the foundation for using Redis in real backend projects, from local development to more advanced environments.
Views: 7
KAHIBARO