简体   繁体   English

如何使用compose,mysql和golang连接docker

[英]How to connect dockers with compose, mysql, and golang

I have a database docker that we'll call mariadb and I also have an web docker that uses golang. 我有一个数据库docker,我们称之为mariadb,我也有一个使用golang的web docker。 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. 我要做的是使用compose连接两个docker,但在我的golang代码中,我必须提前知道数据库docker的ip地址。

Golang main.go: Golang main.go:

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

Docker-compose.yml 泊坞窗,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. 再次澄清一下,我不能简单地使主机成为localhost,因为我使用的数据库是在docker中,通常类似于172.17.0.2或.3但有时会更改。 Thank you! 谢谢!

You can just use your docker service name database , instead of container ip 您可以使用docker服务名称数据库 ,而不是容器ip

UPD You also should share ports like UPD您还应该共享像

"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 UPD2根据mysql docker image doc你还需要定义更多的环境变量,例如MYSQL_DATABASE

You might also consider putting them together in a network. 您也可以考虑将它们放在一个网络中。 This way you are able to access the database on database:3306 from your web container. 这样,您就可以从Web容器访问数据库中的数据库:3306。 This approach has the advantage that database is NOT exposed to the outside world (your local machine) and only containers on the mynet network are able to see it. 这种方法的优点是数据库不会暴露给外部世界(您的本地计算机),只有mynet网络上的容器才能看到它。

version: '3'

services:
  web:
    image: web_docker
    ports:
      - 8080:8080
    depends_on:
      - database
    networks:
      - mynet

  database:
    image: mariadb
    environment:
      - MYSQL_ROOT_PASSWORD=password
    volumes:
      - /data:/var/lib/mysql
    networks:
      - mynet
 networks:
   mynet:
     driver: "bridge"

(code not tested) (代码未经测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM