Docker Compose:无法连接到Redis

时间:2017-09-01 18:41:18

标签: docker redis docker-compose

我在这里关注Docker Compose教程 https://docs.docker.com/get-started/part5/#recap-optional

version: "3"
services:
  web:
    image: example/get-started:part-1
    deploy:
      replicas: 10
      resources:
        limits:
          cpus: "0.1"
          memory: 50M
      restart_policy:
        condition: on-failure
    ports: 
      - "80:80"
    networks:
      - webnet
  visualizer:
    image: dockersamples/visualizer:stable
    ports:
      - "8080:8080"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
    deploy:
      placement:
        constraints: [node.role == manager]
    networks:
      - webnet
  redis:
    image: redis
    ports:
      - "6379:6379"
    volumes:
      - ./data:/data
    deploy:
      placement:
        constraints: [node.role == manager]
    networks:
      - webnet
  driver:
    build: .
    links:
      - redis
networks:
  webnet:

虽然Redis似乎在myvm1上运行,但应用程序无法连接到它,并且出错。

如果重要,这是应用代码:

from flask import Flask
from redis import Redis, RedisError
import os
import socket

redis = Redis(host="redis", db=0, socket_connect_timeout=0, socket_timeout=0)

app = Flask(__name__)

@app.route("/")
def hello():
  try:
    visits = redis.incr("counter")
  except RedisError:
    visits = "<i>cannot connect to redis. Counter disabled</i>"

  html = "<h3>Hello {name}!</h3>" \
         "<b>Hostname:</b> {hostname}<br/>" \
         "<b>Visits:</b> {visits}"
  return html.format(name=os.getenv("NAME", "World"), hostname=socket.gethostname(), visits=visits)

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=80)

虚拟机IP:

  

myvm1 - virtualbox运行tcp://192.168.99.101:2376
  v17.07.0-ce

     

myvm2 - virtualbox正在运行tcp://192.168.99.102:2376
  v17.07.0-CE

Redis在VM上运行时没有错误。

有什么想法吗?网上有很多类似的讨论,但还没有人帮忙。

1 个答案:

答案 0 :(得分:1)

如果redis在VM上运行,则绑定可能不正确。你可以检查它是否绑定在0.0.0.0上,否则你需要编辑redis config配置为0.0.0.0,端口为外部服务连接