13
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

docker-composeでredisコンテナがconnection refusedする

Posted at

TL;DR

コンテナ間の通信がうまくいかなくてかなりハマったdocker学習中なので備忘録
コンテナ間でアクセスする時のホストは127.0.0.1でなくredisというコンテナ名で大丈夫

docker-compose.yml

version: "3.4"

services:
  web: 
    image: nginx:1.15
    links:
      - app
    volumes:
      - ./default.conf:/etc/nginx/conf.d/default.conf
      - ../:/usr/local/dir
    ports:
      - "8888:80"
    env_file: .env

  app:
    build: .
    tty: true
    working_dir: /usr/local/dir
    links:
      - redis
    volumes:
      - ../:/usr/local/dir
    env_file: .env

  redis:
    image: redis:latest
    ports:
      - 6379:6379
    command: redis-server

  • 構成はphp7.3-alpine+nginx+redisでPHPでPredis使用
  • PHP内で以下のようにPredisをnew
public function __construcr($port, $host)
{
    $client = new Predis\Client([
        'scheme' => 'tcp',
        'host'   => $host,
        'port'   => $port,
    ]);
}

  • この$hostの実態は、$_SERVERから取得した127.0.0.1
  • ログを見るとnewはできているものの、Predis呼び出しの時にConnection Refused 127.0.0.1:6379的なメッセージが

解決策

public function __construcr($port, $host)
{
    //このホストを127.0.0.1=>"redis"に
    $client = new Predis\Client([
        'scheme' => 'tcp',
        'host'   => $host,
        'port'   => $port,
    ]);
}

  • この127.0.0.1というのはappコンテナ内だと、そのコンテナ(appコンテナ)のIPアドレス
  • redisコンテナは別なので、ホスト名を明示的にしてあげないとアクセスできない
  • ただ同じネットワーク内なのでredisと明示してあげればOK
13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?