📜  docker run mysql volume - SQL (1)

📅  最后修改于: 2023-12-03 14:40:49.663000             🧑  作者: Mango

Docker Run: MySQL Volume - SQL

Introduction

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.

Prerequisites

Before proceeding, make sure you have Docker installed and have a basic understanding of Docker concepts.

Step 1: Pull the MySQL Image

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.

Step 2: Create a Persistent Volume

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.

Step 3: Run the MySQL Container

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.

Step 4: Connect to the MySQL Container

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.

Step 5: Execute SQL Commands

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.

Conclusion

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.