Deploying MySQL 5.7 in Docker with Host Directory Mounts
To begin, pull the official MySQL 5.7 image from Docker Hub.
docker pull mysql:5.7
For Apple Silicon (M1/M2) Macs, an alternative image may be required:
docker pull mysql/mysql-server:5.6
Next, create the necessary directories on the host machine that will be mounted into the container. These directories will persist configuration, data, and logs.
mkdir -p /docker/mysql/conf /docker/mysql/data /docker/mysql/logs
Now, create and run the MySQL container using the docker run command with specific parameters for port mapping, volume mounting, and enviroment configuration.
docker run \
--name mysql_container \
-p 3306:3306 \
-v /docker/mysql/data:/var/lib/mysql \
-v /docker/mysql/conf:/etc/mysql/conf.d \
-e MYSQL_ROOT_PASSWORD=my_secure_password \
-d mysql:5.7
Parameter Breakdown:
--name: Assigns a custom name to the container.-p: Maps the container's port 3306 to port 3306 on the host.-v: Mounts a host directory to a path inside the container for persistent storage.-e: Sets an environment variable; here it defines the root user's password.-d: Runs the container in detached (background) mode.
To menage containers, you can list running instances and remove them if needed.
# List running containers
docker ps
# Remove a specific container
docker rm <container_id>
To interact with the MySQL server inside the container, you can execute a shell session.
# Start an interactive bash shell inside the container
docker exec -it mysql_container /bin/bash
Once inside the container, you can connect to the MySQL server using the credentials set during creasion.
# Connect to the MySQL server from within the container
mysql -u root -pmy_secure_password
For remote database clients (like Navicat) to connect, you may need to modify the MySQL configuration to allow connections from any host IP address. The configuration file location can vary.
Commmon paths include:
/etc/mysql/my.cnf/etc/mysql/mysql.conf.d/mysqld.cnf
Edit the file and locate the bind-address line, changing it to:
bind-address = 0.0.0.0
If the vi or vim editor is not found inside the container, install it using the package manager.
# Update package lists
apt-get update
# Install the vim text editor
apt-get install -y vim
After modifying the configuration, restart the Docker container for the changes to take effect.
docker restart mysql_container
Following these steps, your MySQL 5.7 instance running in Docker should be accessible remote via the host's IP address on port 3306.