在Docker上本地访问Redis-Docker Compose [英] Access redis locally on docker - docker compose
问题描述
我有两个容器,redis和web.我正在尝试从Web访问Redis容器.什么都行不通.下面是我的docker compose文件
I have two containers, redis and web. I am trying to access the redis container from web. Nothing works. Below is my docker compose file
version: '3.7'
services:
redis:
image: redis:alpine
restart: always
ports:
- "6379"
volumes:
- /private/var/www/redis:/var/www/redis
network_mode: host
web:
build:
context: web
dockerfile: Dockerfile
depends_on:
- redis
ports:
- "127.0.0.1:80:80"
- "127.0.0.1:443:443"
- "127.0.0.1:22:22"
volumes:
- /private/var/www/:/var/www/
networks:
- docker_web_network
networks:
docker_web_network:
driver: bridge
ipam:
driver: default
config:
- subnet: 162.18.1.0/16
当我在Web容器中运行 redis-cli
时,我得到无法以127.0.0.1:6379连接到Redis:连接被拒绝
.
When I run redis-cli
in the web container I get Could not connect to Redis at 127.0.0.1:6379: Connection refused
.
Docker容器
Vs-MacBook-Pro:docker vn$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
36ca1b626a68 docker_web "/bin/sh -c '/usr/sb…" 2 hours ago Up 2 hours 127.0.0.1:22->22/tcp, 127.0.0.1:80->80/tcp, 127.0.0.1:443->443/tcp docker_web_1
d6191f39385a redis:alpine "docker-entrypoint.s…" 2 hours ago Up 2 hours docker_redis_1
redis cli
redis cli
root@36ca1b626a68:/var/www# redis-cli -h docker_redis_1 ping
Could not connect to Redis at docker_redis_1:6379: Name or service not known
推荐答案
在docker容器中使用localhost无效,因为localhost意味着将容器作为自己的容器,因此如果您从Web容器中运行redis-cli,则redis-cli会尝试查找Web容器中的redis而不是redis容器.
Using localhost in docker container is invalid as localhost means for container his own container so if you run redis-cli from within web container redis-cli is trying to find redis in web container instead of redis container.
您需要指定redis服务名称-docker(docker-compose的网络更加具体)将为您解析服务名称为redis的容器IP,因此您应该使用:
U need to specify redis service name - docker (docker-compose's network to be more specific) will resolve for you service name to redis's container IP so you should use:
redis-cli -h redis ping
预期输出为:
PONG
只有两个服务都使用相同的网络模式时,该答案才有效,因此有两种方式:
That answer will only work if both services use same network mode so there are 2 ways:
- 将network_mode:host添加到Web服务中,然后使用Redis的"localhost"就可以了
- 从redis删除network_mode:host,然后再使用"redis"域就可以了
这篇关于在Docker上本地访问Redis-Docker Compose的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!