My docker-compose.yml looks like this:
version: '3'
services:
api:
build:
context: .
dockerfile: Dockerfile
image: api
container_name: app-api
restart: unless-stopped
env_file: ./.env
ports:
- '8080:8080'
volumes:
- ./src
- ./node_modules
command: yarn start
depends_on:
- mysql
mysql:
container_name: app-mysql
restart: always
image: mysql:8.0.21
environment:
MYSQL_ROOT_PASSWORD: 'root'
MYSQL_USER: 'app'
MYSQL_PASS: 'password'
MYSQL_DATABASE: 'appdb'
volumes:
- ./data:/var/lib/mysql
ports:
- '3307:3306'
My .env looks like this:
DB_HOST="mysql" // Tried 127.0.0.1, 0.0.0.0
DB_PORT="3306"
DB_USER="app"
DB_PASSWORD="password"
DB_NAME="appdb"
NODE_ENV="DEV"
Error I'm getting from the service:
{"message":"Database connection failed with error Error: getaddrinfo ENOTFOUND \"mysql\"","level":"info","timestamp":"2020-07-27T03:57:55.524Z"}
I can connect with root from MySQL Workbench, I can't connect with user app. If the api is started without being in a docker container, it can connect to local db.
Seems like it just can't resolve the host at all, is this a DNS issue? I can't remember if I had the same issue when mysql wasn't dockerized, but it couldn't connect to a db that is outside a container. What am I doing wrong.
Edit: commenting out the whole mysql service has no impact at all, error message is same.
I built a simpler API service to test the setup -- it's working correctly. Must've been something with the boilerplate API I was using.
If anybody's looking, things I discovered:
host.docker.internal instead of 127.0.0.1 or mysql works -- connects to a db server on your machine../data folder was actually not empty, mysql dumped all its stuff there it seems like.Docker interprets double quotes in a .env file differently than a unix system. Specifically - double quotes are considered part of the string.
https://docs.docker.com/compose/env-file/
There is no special handling of quotation marks. This means that they are part of the VAL.
Remove the quotes in your .env file and you'll be fine.
Had the same issue. I am using Docker Secrets via docker-compose to load the mysql host into my Node app and had a newline at the end of my secret file for the mysql hostname.
... sooo, in case you are using Docker Secrets, you might want to check if there is an unwanted newline at the end of your secret file.