问题
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
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 containers
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
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
回答1:
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.
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
expected output is:
PONG
Edit:
That answer will only work if both services use same network mode so there are 2 ways:
- Add network_mode:host to web service and then "localhost" for redis will be fine
- Remove network_mode:host from redis and then "redis" domain will be fine
来源:https://stackoverflow.com/questions/52246220/access-redis-locally-on-docker-docker-compose