Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect dockers with compose, mysql, and golang

Tags:

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!

like image 495
Lorraine Avatar asked Aug 17 '17 13:08

Lorraine


People also ask

How do I connect to a MySQL Docker container?

Here are the steps you can follow to install the Dockerhub MySQL Container: Step 1: Pull the Docker Image for MySQL. Step 2: Deploy and Start the MySQL Container. Step 3: Connect with the Docker MySQL Container.

Do you need Dockerfiles with Docker compose?

Both the Dockerfile and docker-compose are important resources in the development and deployment of cloud-native applications. But knowing the difference between docker-compose and the Dockerfile is important. The Dockerfile is used to build images, while docker-compose helps you run them as containers.


1 Answers

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

like image 82
Andrei Avatar answered Oct 10 '22 22:10

Andrei