Tutorial
How to Deploy and Run Redis in a Docker Container
February 25, 20264 minute read
TL;DR:Pull the official Redis image withdocker pull redis:latest, then run it withdocker run -d --name my-redis -p 6379:6379 redis:latest. Add-v /path/to/data:/dataand-e REDIS_ARGS="--appendonly yes"for persistent storage.
#What you'll learn
- How to pull and run the Redis Docker image
- How to connect to Redis inside a container using
redis-cli - How to persist data with Docker volumes
- How to set a Redis password in Docker
- How to run Redis with Docker Compose
#Prerequisites
- Docker installed on your system
- Basic familiarity with the command line
#How do I pull the Redis Docker image?
Before running a Redis container, pull the latest official Redis image from Docker Hub:
You can verify the image was downloaded by listing your local Docker images:
#How do I run Redis in a Docker container?
Execute the following command to run the Redis container in the background:
-druns the container in detached (background) mode--name my-redisassigns a name to the container-p 6379:6379maps the container's Redis port to your host machineredis:latestspecifies the Docker image
Verify the container is running:
You should see output similar to:
#How do I connect to Redis inside a Docker container?
Use
docker exec to open an interactive shell inside the running container, then launch redis-cli:Test the connection:
You can also run Redis commands directly without entering the interactive shell:
#How do I persist data with Docker volumes?
By default, data stored in a Redis container is lost when the container is removed. To persist data, mount a Docker volume and enable append-only file (AOF) persistence:
-v redis-data:/datacreates a named Docker volume mapped to Redis's data directory--appendonly yesenables AOF persistence so every write operation is logged to disk
You can also use a bind mount to store data in a specific host directory:
#How do I set a Redis password in Docker?
To secure your Redis container with a password, pass
--requirepass via the REDIS_ARGS environment variable:Connect with authentication:
#How do I run Redis with Docker Compose?
For more complex setups, Docker Compose provides a declarative way to configure and run Redis. Create a
docker-compose.yml file:Start the service:
Stop and remove the containers:
Docker Compose is especially useful when Redis is part of a larger application stack. See How to build and run a Node.js application using Nginx, Docker and Redis for a full multi-container example.
#Next steps
- Learn how to build a Node.js app with Nginx, Docker, and Redis
- Explore Redis persistence options to choose between RDB snapshots and AOF
- Read about Redis configuration for advanced tuning