duanjuhuo8772 2017-08-17 13:40
浏览 306

如何将docker与compose,mysql和golang连接

I have a database docker that we'll call mariadb and I also have an web docker that uses golang. What I'm trying to do is connect the two dockers using compose, but in my golang code, I have to know the database docker's ip address ahead of time.

Golang main.go:

db, err := sql.Open("mysql", 
"root:passsword@tcp(<should_be_database_docker_ip>:3306)/database")

Docker-compose.yml

version: '3'

services:
  web:
    image: web_docker
    ports:
      - "8080"
    depends_on:
      - database

  database:
    image: mariadb
    ports:
      - "3306"
    environment:
      - MYSQL_ROOT_PASSWORD=password
    volumes:
      - /data:/var/lib/mysql

Again for clarification, I cannot simply make the host be localhost because the database I'm using is in a docker and is usually something like 172.17.0.2 or .3 but sometimes it changes. Thank you!

  • 写回答

2条回答 默认 最新

  • drn34916 2017-08-17 14:08
    关注

    You can just use your docker service name database, instead of container ip

    UPD You also should share ports like

    "3306:3306"
    

    or ports will maps randomly

    see output of

    docker-compose ps
    

    UPD2 according to mysql docker image doc you also need to define more environment variables, eg MYSQL_DATABASE

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题