MySQL in Docker Compose
Running MySQL using Docker makes it effortless, and it's even easier to run and manage MySQL when using Docker Compose.
Follow these steps to run MySQL with Docker Compose:
- Add the service below to a Compose file:
docker-compose.yml
services:
mysql:
image: mysql:8
volumes:
- ./mounted_data/mysql:/var/lib/mysql
environment:
- MYSQL_RANDOM_ROOT_PASSWORD=yes
- MYSQL_DATABASE=app
- MYSQL_USER=app_user
- MYSQL_PASSWORD=app_user
ports:
- "127.0.0.1:3306:3306"
restart: always
- Create the directory on the host where MySQL data will be retained
mkdir -p mounted_data/mysql
- Start the service
docker compose up -d mysql
- Use the following connection string to connect to the database:
mysql://app_user:app_user@localhost:3306/app
(If you're connecting from another container in the same Compose file, use mysql as the hostname instead of localhost)
tip
The service is exposed only to the host machine, so you'll need to SSH into the host to connect from outside the host machine. For example, when using MySQL Workbench, etc.
info
The root password is randomly generated and stored in the logs when the container is started.
Run docker compose logs mysql to view the logs.