connecting to a docker-compose mysql container denies access but docker running same image does not

Environment variables in docker-compose.yml file should not have quotes when using array definition:

db:
  image: mysql:5.7
  ports:
    - "3306:3306"
  environment:
    - MYSQL_ROOT_PASSWORD=secret
    - MYSQL_USER=django
    - MYSQL_PASSWORD=secret
    - MYSQL_DATABASE=myAppDB

If you use them in your docker-compose.yml file:

db:
  image: mysql:5.7
  ports:
    - "3306:3306"
  environment:
    - MYSQL_ROOT_PASSWORD="secret"
    - MYSQL_USER="django"
    - MYSQL_PASSWORD="secret"
    - MYSQL_DATABASE="myAppDB"

and run:

$ docker-compose up -d

and enter running container:

$ docker-compose exec db /bin/bash

you will see the output:

root@979813643b0c:/# echo $MYSQL_ROOT_PASSWORD                                                                                                                                              
"secret"

I am using the official mysql image with docker-compose and not having a problem. The only difference in my compose file is that I am using a dictionary instead of an array:

environment:
  MYSQL_ROOT_PASSWORD: secret
  MYSQL_USER: django
  MYSQL_PASSWORD: secret
  MYSQL_DATABASE: myAppDB

I have noticed that the compose file documentation is still stuck in V1 in some places, so you could try this, if you're using V2. Otherwise, for debugging you can use docker-compose exec to interact with the container created by compose directly.

docker-compose exec db /bin/bash will get you a shell on the container that is giving you trouble and you can check things like SHOW GRANTS FOR django@'%' or whether the ports are being forwarded correctly. I hope this helps.


I had a similar issue, and this helped me:

https://github.com/docker-library/mysql/issues/51#issuecomment-76989402

Have you changed the passwords since you first tried running the containers? docker-compose does extra work to preserve volumes between runs (thus preserving the database); you may want to try docker-compose rm -v to delete everything and try starting it up again.