📅  最后修改于: 2023-12-03 14:40:49.663000             🧑  作者: Mango
In Docker, the docker run
command is used to create and run a new container from a selected image. This tutorial focuses on running a MySQL container with volume and executing SQL commands within it.
Before proceeding, make sure you have Docker installed and have a basic understanding of Docker concepts.
To start, you need to pull the MySQL image from the Docker Hub. Open a terminal and execute the following command:
$ docker pull mysql
This command will download the latest MySQL image from the Docker Hub.
To persist MySQL data even if the container is stopped or removed, we can create a persistent volume in Docker using the docker volume
command. Run the following command to create a named volume:
$ docker volume create my_mysql_volume
Replace my_mysql_volume
with your desired volume name.
Next, we can run the MySQL container with the volume created in the previous step. Execute the following command:
$ docker run -d --name mysql-container -e MYSQL_ROOT_PASSWORD=mysecretpassword -v my_mysql_volume:/var/lib/mysql mysql
This command will start a new container named mysql-container
, set the root password to mysecretpassword
, and map the my_mysql_volume
volume to the MySQL container's data directory.
To connect to the MySQL container and execute SQL commands, we need to use another container. We can accomplish this using the official MySQL client container. Run the following command:
$ docker run -it --network container:mysql-container mysql mysql -h localhost -u root -p
This command will start a new container in the same network as the mysql-container
and connect it to the MySQL server running inside the mysql-container
.
Once connected to the MySQL server, you can execute any SQL commands as you would in a typical MySQL environment. For example, to create a new database, use the following SQL command:
CREATE DATABASE mydatabase;
Remember to end each SQL command with a semicolon.
By following the steps outlined in this tutorial, you can run a MySQL container with a volume and execute SQL commands within it. This approach allows you to persist your MySQL data and easily interact with the database using a separate container.
Make sure to explore more options and features of Docker and MySQL to fully utilize the capabilities they offer.