I have run a redis container using this command: docker run -d --name redis -p 6379:6379 redis
.
and I have run my Django app using this command: docker run -it -p 8000:8000 voucher
.
and my connection redis url is redis://redis:6379/1
.
But i cannot seem to connect to redis here is my error:
redis.exceptions.ConnectionError: Error -2 connecting to redis:6379. Name or service not known.
PS: I'm not using docker-compose
CodePudding user response:
Both Container have to be in the same Docker network
to be able to communicate via the Container names.
docker run -d --name redis --network your-network -p 6379:6379 redis
docker run -it --network your-network -p 8000:8000 voucher
CodePudding user response:
I have fix that by changing my redis connection url to redis://172.17.0.2:6379/1. But why is that ? How can I use container names instead of IPs?
This is your host IP. You have a few ways to solve your problem.
1 - Use the hardcoded IP as you did.
2 - Use docker link to connect applications like:
docker run --name my-redis-application --link my-redis-container:redis -d centos
3 - You can create a redis.conf with the follow content:
bind 0.0.0.0
and use it in the startup like:
docker run -v $(pwd):/usr/local/etc/redis/ --name redis -p 6379:6379 -d redis redis-server /usr/local/etc/redis/redis.conf
4 - You can use docker-compose to link then better, like in #2.
CodePudding user response:
Did you defined redis info in .env file? That could lead to connection error too.
/.env
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=yourpassword/blank
REDIS_PORT=6379
CodePudding user response:
I have fix that by changing my redis connection url to redis://172.17.0.2:6379/1
.
But why is that ?
How can I use container names instead of IPs?
CodePudding user response:
I think the better option is docker-compose. if you like to use docker-compose here is the answer.
docker-compose.yml
version: "3.8"
services :
redis:
image : redis
container_name : redis
restart : unless-stopped
ports:
- 6379:6379
voucher:
build:
image:voucher
ports:
- 8000:8000
depends_on:
- redis
now you can connect to Redis using the service name "redis".