A while ago, I wrote an article about using Docker to run the mysql container for mysql support in local development (or maybe production). The downside of that approach was that all related data was deleted if you deleted the container. Generally, for local development, it is not a major problem as there is no production data, but it is a hassle to set up DB again.
To resolve this, we must bind a volume (directory) from our system to a directory in the docker container. You can read more about volumes here.
To achieve this we need to create 2 files.
- DockerFile
- docker-compose.yml
Create DockerFile
Create a new file with the name DockerFile
. Add the following lines of code to the file.
# Use the official MySQL image as the base image FROM mysql:latest LABEL authors="msamgan" # update with your name. # Set the default environment variables (customize as needed) ENV MYSQL_ROOT_PASSWORD=root ENV MYSQL_DATABASE=my_database ENV MYSQL_USER=user ENV MYSQL_PASSWORD=password # Expose the default MySQL port EXPOSE 3306
Create docker-compose.yml
Create a new file with the name docker-compose.yml
and add the following content to the file.
services: # Define services
mysql: # Define MySQL service
build: . # Build MySQL image from Dockerfile in the same directory
container_name: mysql_service # Name the container
environment: # Set environment variables
MYSQL_ROOT_PASSWORD: root # Set MySQL root password
MYSQL_DATABASE: my_database # Create a database named my_database
MYSQL_USER: user # Create a user named user
MYSQL_PASSWORD: password # Set user password
ports: # Expose MySQL port
- "3306:3306" # Map container port 3306 to host port 3306
volumes: # Attach volumes
- ./mysql_data:/var/lib/mysql # Attach volume to persist MySQL data in the same directory
Now, all you have to do is run
docker compose up -d
and you are good to go. All the mysql data and databases can be found in the mysql_data
directory, and you will not lose it even if you delete the container.