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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With