Local MySQL container using docker-compose
You'll learn how to set up MySQL container for your local development using docker compose. You can easily start it and shut it down when you don't need it and your data won't get lost. Very useful when you just want to create a MySQL database quick for your local development.
Directory structure
- ./db
- ./db/sql/
- ./docker-compose.yml
Explanation
Our MySQL data will live inside ./db directory.
You can put any sql file into ./db/sql directory, it will run automatically when during build. (It's useful when you want to restore data from some dump file)
./docker-compose.yml is our docker compose configuration file.
Code
docker-compose.yml
version: '3'services:
# MySQL
db:
image: mysql:5.7
container_name: mysql_host
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: test
MYSQL_USER: docker
MYSQL_PASSWORD: docker
TZ: 'Asia/Tokyo'
command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
volumes:
- ./db/data:/var/lib/mysql
- ./db/sql:/docker-entrypoint-initdb.d
ports:
- 3306:3306
How to run
docker-compose up -d
How to stop
docker-compose down
Additional info
You will be able to connect to your database called test, on your localhost port 3306, with the user named docker using the password docker.
If you put any sql file inside ./db/sql/ folder, you will find that it got executed.
You will find your data is still available after you shut down and start your container again, since we specify volumes in our docker compose yaml file.