Docker Redis Connection refused

前端 未结 5 1231
情书的邮戳
情书的邮戳 2021-01-31 04:59

I\'m trying to access Redis server through the code and it\'s not connecting. But if i bash to the redis container i can access the redis-cli.

docker-compose.yml looks l

5条回答
  •  [愿得一人]
    2021-01-31 05:27

    Your Problem

    Docker Compose creates separated docker container for different services. Each container are, logically speaking, like different separated computer servers that only connected with each other through docker network.

    Consider each boxes in this diagram as an individual computer, then this is practically what you have:

    +----------------------------------------------------------+
    |                       your machine                       |
    +----------------------------------------------------------+
                                   |                    
            +------ (virtual network by docker) -------+
            |                      |                   |
    +-----------------+ +-------------------+ +----------------+
    | "php" container | | "redis" container | | "db" container |
    +-----------------+ +-------------------+ +----------------+
    

    Your PHP container doesn't see any redis in "localhost" because there is no redis in it. Just like it would't see any MySQL in "localhost". Your redis is running in the "redis" container. Your MySQL is running in your "db" container.

    The things that confuses you is the port binding directives (i.e. ports in this definition):

    redis:
      build:
        context: .
        dockerfile: Dockerfile_redis
      ports:
        - "6379:6379"
    

    The port 6379 of the "redis" container is binded to your computer, but to your computer ONLY. Other container doesn't have the same access to the port bindings. So even your computer can connect it with '127.0.0.1:6379', the php container cannot do the same.

    Solution

    As described in Networking in Docker Compose, each docker compose container can access other container by using the service name as hostname. For example, your programming running by service php can access your MySQL service with the hostname db.

    So you should connect redis with its hostname redis

    $redis = new \Redis();
    try {
        $redis->connect('redis', 6379);
    } catch (\Exception $e) {
        var_dump($e->getMessage())  ;
        die;
    }
    

提交回复
热议问题