Web服务器无法通过docker compose连接到redis

fnatzsnv  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(428)

我正在尝试通过同一网络上的Web服务器连接到docker网络上的redis示例。我的代码在go中,我正在使用docker-compose.yml:

thor-redis:
    image: redis:5.0.7
    networks:
      - thorcast
    ports:
      - "6380:6379"
    volumes:
      - ./redis.conf:/usr/local/etc/redis.conf
    entrypoint: redis-server /usr/local/etc/redis.conf
thorcast-server:
    build: ../../thorcast-server
    volumes:
      - ../../thorcast-server:/app/thorcast-server
    networks:
      - thorcast
    ports:
      - "8000:8000"
    env_file:
      - ../../thorcast-server/env.list

env.list文件的相关部分:

REDIS_HOST=thor-redis
REDIS_PORT=6380
REDIS_DB=0
REDIS_PASSWORD=redis_pass

我的应用程序中连接到redis的代码是:

a.Redis = redis.NewClient(&redis.Options{
    Addr:       fmt.Sprintf("%s:%s", conf.redisHost, conf.redisPort),
    Password:   conf.redisPassword,
    DB:         conf.redisDb,
})

我填充conf的代码是:

type config struct {
    sqlUsername     string
    sqlPassword     string
    sqlHost         string
    sqlPort         string
    sqlDbName       string
    redisPassword   string
    redisHost       string
    redisPort       string
    redisDb         int
}
// method to initialize config struct from environment variables
func (conf *config) configure() {
    conf.sqlUsername = os.Getenv("THORCAST_DB_USERNAME")
    conf.sqlPassword = os.Getenv("THORCAST_DB_PASSWORD")
    conf.sqlHost = os.Getenv("THORCAST_DB_HOST")
    conf.sqlPort = os.Getenv("THORCAST_DB_PORT")
    conf.sqlDbName = os.Getenv("THORCAST_DB_NAME")
    conf.redisPassword = os.Getenv("REDIS_PASSWORD")
    conf.redisHost = os.Getenv("REDIS_HOST")
    conf.redisPort = os.Getenv("REDIS_PORT")
    conf.redisDb, _ = strconv.Atoi(os.Getenv("REDIS_DB"))
}
var conf = config{}

type App struct {
    Router *mux.Router
    Logger http.Handler
    DB     *sql.DB
    Redis  *redis.Client
}

在redis.conf文件中,没有指定绑定IP,并且requirepass设置为与redis\u pass相同的值。此外,我在服务器上看到的错误是:

{"error":"dial tcp 172.21.0.5:6380: connect: connection refused"}

当我检查redis映像时,我可以确认它有这个ip地址:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' dev_thor- 
redis_1
172.21.0.5

当我尝试通过redis cli从本地计算机连接时,我可以毫无问题地访问服务器。我在google上搜索过,试图找到类似的问题,但它们似乎都与试图通过localhost访问redis的人有关,而我不想这样做。非常感谢您的帮助。

ubby3x7f

ubby3x7f1#

你可能忘了从网络视角将你的应用程序与redis链接

thor-redis:
        image: redis:5.0.7
        networks:
          - thorcast
        ports:
          - "6380:6379"
        volumes:
          - ./redis.conf:/usr/local/etc/redis.conf
        entrypoint: redis-server /usr/local/etc/redis.conf
    thorcast-server:
        build: ../../thorcast-server
        volumes:
          - ../../thorcast-server:/app/thorcast-server
        networks:
          - thorcast
        ports:
          - "8000:8000"
        env_file:
          - ../../thorcast-server/env.list
        links:          # <-- Add this
          - thor-redis  # <-- Add this

相关问题