Go语言 当“docker-compose up --build”时,得到错误:“拨打tcp 127.0.0.1:6379:连接:连接被拒绝”

bjp0bcyl  于 2023-06-19  发布在  Go
关注(0)|答案(1)|浏览(205)

我有一个Golang服务器,一个Postgresql数据库和Redis。我通过docker-compose运行所有的东西,服务器和数据库连接成功,但服务器和Redis没有。很不幸,我找不到原因。我总是得到一个错误,但Redis已经准备好接受连接。以下是我的docker-compose:

services:
  postgres:
    container_name: postgres
    image: postgres:latest
    environment:
      POSTGRES_DB: links
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    ports:
      - "5432:5432"
    volumes:
      - postgres-vol:/var/lib/postgresql/data
      - ./sql-scripts:/docker-entrypoint-initdb.d
    networks:
      - techno
  redis:
    container_name: redis
    image: redis:latest
    ports:
      - 6379:6379
    networks:
      - redis_test
  app:
    container_name: myapp
    build:
      context: ./
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    depends_on:
      - postgres
      - redis
    restart: always
    volumes:
      - ./config/config.yml:/app/config/config.yml
      - ./internal/repository/migration:/app/migration
      - ./links.json:/app/links.json
    networks:
      - techno
      - redis_test
    environment:
      - APP_MODE=DEV
networks:
  techno:
    driver: bridge
  redis_test:
    driver: bridge

volumes:
  postgres-vol:```

这就是我尝试连接的方式:

client := redis.NewClient(&redis.Options{
        Addr:        "localhost:6379",
        DB:          0,
        DialTimeout: 100 * time.Millisecond,
        ReadTimeout: 100 * time.Millisecond,
    })

我试过将localhost:6379更改为redis:6379,但仍然不起作用。

2w2cym1i

2w2cym1i1#

我们需要您的完整docker-compose.yml来了解您的上下文。但是如果我错了,请纠正我,你也在Docker容器中运行你的Go应用程序,对吗?如果是这样的话,那么把它们都放在同一个Docker网络中,比如:

version: "3"

networks:
  example:
    driver: bridge

services:
  redis:
    image: redis:latest
    ports:
      - 6379:6379
    networks:
      - example

  api:
    {api_setup}
    networks:
      - example

你的联系应该是
connection.go

client := redis.NewClient(&redis.Options{
        Addr:        "redis:6379",
        DB:          0,
        DialTimeout: 100 * time.Millisecond,
        ReadTimeout: 100 * time.Millisecond,
    })

相关问题