'Docker-compose,My app can't connect to the database

Here is my docker-compose file

    version: '3'
services:
  mysql:
    image: mysql:5.7
    command: --default-authentication-plugin=mysql_native_password
    container_name: mysql
    hostname: mysqlServiceHost
    network_mode: bridge
    ports:
    - "3306:3306"
    restart: on-failure
    volumes:
    - ./mysql_data:/var/lib/mysqldocker
    - ./my.cnf:/etc/mysql/conf.d/my.cnf
    - ./mysql/init:/docker-entrypoint-initdb.d/
    - ./shop.sql:/docker-entrypoint-initdb.d/shop.sql
    environment:
    - MYSQL_ROOT_PASSWORD=a123456
    - MYSQL_DATABASE=shop

  redis:
    image: redis:3
    container_name: redis
    host: redis
    hostname: redisServiceHost
    network_mode: bridge
    restart: on-failure
    ports:
    - "6379:6379"
  golang:
    build: .
    restart: always
    network_mode: bridge
    ports:
    - "8080:8080"
    depends_on:
      - mysql
      - redis
    links:
      - mysql
      - redis
    volumes:
    - /xiangmu/go/src:/go
    tty: true

This is my go language code to connect mysql:

mysqladmin="root"
mysqlpwd="a123456"
mysqldb="shop"
    DB, err = gorm.Open("mysql",mysqladmin+":"+mysqlpwd+"@tcp(mysqlServiceHost)/"+mysqldb+"?charset=utf8"+"&parseTime=True&loc=Local")

This is my go language code to connect redis:

config := map[string]string{
            "key":      beego.AppConfig.String("redisKey"),
            "conn":     "redisServiceHost:6379",
            "dbNum":    beego.AppConfig.String("redisDbNum"),
            "password": beego.AppConfig.String("redisPwd"),
        }
        bytes, _ := json.Marshal(config)

        redisClient, err = cache.NewCache("redis", string(bytes))

they have the same problem:

dial tcp: lookup redisServiceHost on 100.100.2.136:53: no such host
dial tcp: lookup mysqlServiceHost on 100.100.2.136:53: no such host

I have successfully connected to redis once, that time I used the IP address of the redis container, but after starting docker-compose again, I can't connect to it. It seems to be a host problem. I tried many methods to no avail. .



Solution 1:[1]

All services in the same docker-compose file will join the same network, each container can look up service name(redis and mysql in your example) to get back the appropriate container’s IP address.

So you can use the service name, try change to:

    DB, err = gorm.Open("mysql",mysqladmin+":"+mysqlpwd+"@tcp(mysql)/"+mysqldb+"?charset=utf8"+"&parseTime=True&loc=Local")

            "conn":     "redis:6379",

For more details, please check https://docs.docker.com/compose/networking/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zzn