Docker MySQL Compose File with Volume Example

Running MySQL using Docker Compose yml File with Volume

In order to create a docker

File Name: mysql-docker-compose.yml
version: '3.8'
    image: mysql:latest
    restart: always
      - "./.mysql-data/db:/Users/code2care/docker-volumes"
      - 3306:3306
      MYSQL_ROOT_PASSWORD: root123
      MYSQL_DATABASE: my_uat
      MYSQL_USER: mysqluser
      MYSQL_PASSWORD: mysqluser123

Docker MySQL Compose file details:

  • version: It is the version of the docker-compose file, this should be based on your docker engine - know more: Compatibility matrix
  • services: To define the list of services, we just have one here with name ie. uat_mysql_db,
  • image: The name of the MySQL docker image with the tag as the latest, you can choose a tag with a specific version of MySQL e.g. 5.7 etc:
  • restart: We always want to restart the container if it fails for some reason.
  • volumes: We want to store the MySQL files on the local device at the specified location.
  • ports: Exposing the local MySQL 3306 port to host device 3306 port.
  • environment: Defined the MySQL root user password and optional superuser and password.

Running the MySQL Docker Compose file

Make sure you run the command from the directory where you have the .yml file.

% docker compose -f mysql-docker-compose.yml up

Logging into the MySQL prompt using root user

# docker exec -it my-docker-scripts-uat_mysql_db-1 /bin/sh

sh-4.4# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.30 MySQL Community Server - GPL
mysql>  show databases;
| Database           |
| information_schema |
| my_uat             |
| mysql              |
| performance_schema |
| sys                |
5 rows in set (0.02 sec)

Have Questions? Post them here!
Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.