这是我当前的docker-compose.yml:

version: "2.0"
services:
    redis:
      image: redis
      container_name: framework-redis
      ports:
        - "127.0.0.1:6379:6379"
    web:
      image: myContainer:v1
      container_name: framework-web
      depends_on:
        - redis
      volumes:
        - /var/www/myApp:/app
      environment:
        LOG_STDOUT: /var/log/docker.access.log
        LOG_STDERR: /var/log/docker.error.log
      ports:
        - "8100:80"


我尝试了不同的设置;例如:不使用端口值进行Redis,而是使用0.0.0.0,切换到暴露选项。

如果我尝试使用主机上的127.0.0.1进行连接,则可以正常工作,但是由于我的应用程序容器连接失败而失败。

有什么想法吗?

最佳答案

如果要从framework-redis访问framework-web,则需要使用ip(或容器名称,即framework-redis)和framework-redis的端口访问它。由于它将位于docker bridge之后,因此将172.17.0.0/16范围内的IP分配给framework-redis。您可以使用该IP或更好的IP地址,只需提供容器名称以及6379端口即可。

 $ cat docker-compose.yml
version: "2.0"
services:
    redis:
      image: redis
      container_name: framework-redis
    web:
      image: redis
      container_name: framework-web
      depends_on:
        - redis
      command: [ "redis-cli", "-h", "framework-redis", "ping" ]
  $
  $ docker-compose up
Recreating framework-redis ... done
Recreating framework-web   ... done
Attaching to framework-redis, framework-web
framework-redis | 1:C 09 Dec 2019 19:25:52.798 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
framework-redis | 1:C 09 Dec 2019 19:25:52.798 # Redis version=5.0.6, bits=64, commit=00000000, modified=0, pid=1, just started
framework-redis | 1:C 09 Dec 2019 19:25:52.798 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
framework-redis | 1:M 09 Dec 2019 19:25:52.799 * Running mode=standalone, port=6379.
framework-redis | 1:M 09 Dec 2019 19:25:52.800 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
framework-redis | 1:M 09 Dec 2019 19:25:52.800 # Server initialized
framework-redis | 1:M 09 Dec 2019 19:25:52.800 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
framework-redis | 1:M 09 Dec 2019 19:25:52.800 * DB loaded from disk: 0.000 seconds
framework-redis | 1:M 09 Dec 2019 19:25:52.800 * Ready to accept connections
framework-web | PONG
framework-web exited with code 0


如您在上面看到的,我收到了PONG命令的PING

其他一些要点:


portsHOST_PORT:CONTAINER_PORT形式编写。您不需要提供IP(如@coulburton在评论中指出的那样)。
如果您仅从framework-redis访问framework-web,则无需发布端口(即,端口部分中的6379:6379)。仅当我们要从其他网络(例如,主机或其他物理机)访问在容器网络(据我所知默认为172.17.0.0/16)中运行的应用程序时,才需要发布端口。

关于docker - 在docker-compose中使用Redis时连接被拒绝,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59255062/

10-16 23:47