I have a python/sqlalchemy app that I want to make communicate with a mysql database, both of which are in docker containers, and both of which launched via docker-compose.
I believe the correct way to establish credentials for the mysql database is using environment variables pulled from a config file. I believe this will allow me to easily develop locally, and then when I deploy the app, easily create a config file on the server, though I'm not entirely sure about that process yet.
For now, my mysql database's password for root
isn't being accepted, whether the origin is the python server, or docker exec -it
. That being said, the environment variable MYSQL_ROOT_PASSWORD
does appear to be properly accessible in the mysql container. I'll demonstrate:
/docker-compose.dev.yml
version: '3.8'
services:
api:
build:
context: ./backend/
ports:
- 5000:5000
env_file:
- .dev.env
networks:
- local-net
depends_on:
- mysqldb
mysqldb:
image: mysql
# container_name: "mysqldb"
ports:
- 3306:3306
env_file:
- .dev.env
volumes:
- mysql:/var/lib/mysql
- mysql_config:/etc/mysql
networks:
- local-net
frontend:
build:
context: ./frontend/
ports:
- 8080:8080
volumes:
mysql:
mysql_config:
networks:
local-net:
driver: bridge
I believe that the proper way to pass in an env file is via env_file
, and that appears to be working:
/.dev.env
MYSQL_ROOT_PASSWORD='password'
MYSQL_USER=root
MYSQL_HOST=mysqldb
MYSQL_DB='remixguesser'
MYSQL_PORT=3306
I believe it's working because if I do the following, it returns password
$ docker exec -it game-remix-guesser_mysqldb_1 bash
root@206acfa56847:/# echo $MYSQL_ROOT_PASSWORD
password
However, that's not the password for user root
root@206acfa56847:/# mysql -u root -p
Enter password:
And then input password
I get:
ERROR 1045 (28000): Access denied for user 'root'@'(ip)' (using password: YES)
So, password
isn't the password for user root
despite my intentions. I believe this leading to me, in python, getting the error:
RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods
Despite having confirmed that I have access to the same environment variables from the environment file as the mysql server does:
/backend/app/database.py
username = os.getenv('MYSQL_USER')
password = os.getenv('MYSQL_ROOT_PASSWORD')
host = os.getenv('MYSQL_HOST')
port = os.getenv('MYSQL_PORT')
DB_NAME = os.getenv('MYSQL_DB')
print(username)
print(password)
print(host)
print(port)
SQLALCHEMY_DATABASE_URL = f"mysql+pymysql://{username}:{password}@{host}:{port}"
Prints, before getting the error:
api_1 | root
api_1 | password
api_1 | mysqldb
api_1 | 3306
How can I properly establish a mysql server docker image in a way that allows me to share credentials with, and connect to it from, my python server? I believe the answer to that is "using a .env
file," and so my question is thus How can I properly set up a user and password for a mysql docker image using a .env config file passed in via docker-compose?