Connecting to Redis running in Docker Container from Host machine
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
To connect to Redis running in a Docker container from your host machine, you must publish port 6379 when starting the container with -p 6379:6379. This maps the container's Redis port to the same port on your host, allowing redis-cli, application code, and GUI tools to connect via localhost:6379. Without the port mapping, the container's network is isolated and unreachable from the host.
Starting Redis with Port Mapping
--name my-redis— gives the container a memorable name-p 6379:6379— maps host port 6379 to container port 6379-d— runs in detached (background) moderedis— uses the official Redis image
Connecting from the Host
Using a Different Host Port
This is useful when you already have a local Redis instance on port 6379.
Docker Compose
Connecting with a Password
Docker Compose with a password:
Connecting from Application Code
Python
Node.js
Java (Jedis)
Connecting from Another Container
Containers on the same Docker network can connect by container name:
The app container connects to redis:6379 using the service name as the hostname. Port mapping (ports:) is only needed for host-to-container access.
Custom Redis Configuration
Verifying the Connection
Common Pitfalls
- Forgetting
-p 6379:6379: Without port mapping, the host cannot reach the container's Redis. Container ports are isolated by default. Always include-pfor host access. - Redis
binddirective: If using a customredis.conf, ensurebind 0.0.0.0(notbind 127.0.0.1). The defaultbind 127.0.0.1only accepts connections from inside the container, rejecting host connections. - Firewall blocking the port: On Linux,
iptablesorufwmay block Docker's published ports. Check withsudo ufw statusand allow port 6379 if needed. - Port already in use: If a local Redis instance is already running on port 6379, Docker fails to bind the port. Either stop the local Redis (
sudo systemctl stop redis) or map to a different host port (-p 6380:6379). - Using
localhostfrom another container: Containers should connect by service name (redis:6379), notlocalhost. Inside a container,localhostrefers to that container itself, not the host or other containers.
Summary
- Use
-p 6379:6379when starting the container to expose Redis to the host - Connect with
redis-cli -h localhost -p 6379or any Redis client library - Use Docker Compose with
ports: ["6379:6379"]for reproducible setups - Container-to-container connections use the service name, not port mapping
- Set
bind 0.0.0.0in customredis.confto accept external connections

