📅  最后修改于: 2023-12-03 15:00:29.066000             🧑  作者: Mango
Docker is a containerization platform that allows developers to package an application and all its dependencies into a single, self-contained unit. One popular use case for Docker is to run MySQL servers locally for testing.
In this guide, we will walk through the process of opening a terminal in a Docker container running a MySQL server and executing SQL commands.
To follow along with this guide, you will need the following:
Before we can run a MySQL server in a Docker container, we need to pull the MySQL Docker image. Run the following command in your terminal:
docker pull mysql
This will download the latest MySQL Docker image to your local machine.
Now that we have the MySQL Docker image, we can start a new container using the following command:
docker run -d -p 3306:3306 --name mysql-server -e MYSQL_ROOT_PASSWORD=mysecretpassword mysql:latest
Here's what's happening in the command above:
docker run
command is used to start a new container.-d
flag tells Docker to run the container in the background (detached mode).-p 3306:3306
flag maps port 3306 on the host machine to port 3306 in the container (MySQL's default port). This allows us to connect to the MySQL server using a database client on our local machine.--name mysql-server
flag gives the container a name that we can use to refer to it later.-e MYSQL_ROOT_PASSWORD=mysecretpassword
flag sets the MySQL root user's password to "mysecretpassword".mysql:latest
specifies the name and tag of the Docker image we want to use (latest version).To open a terminal in the container, run the following command:
docker exec -it mysql-server bash
This tells Docker to execute the bash
command inside the mysql-server
container, with the -it
flag enabling an interactive terminal session.
Now that we're inside the container's terminal, we can connect to the MySQL server using the mysql
command:
mysql -u root -p
Enter the password you set earlier ("mysecretpassword") when prompted.
Once you're connected to the MySQL server, you can execute SQL commands as you normally would. For example, you can create a new database with the following command:
CREATE DATABASE mydatabase;
You can also query an existing database, for example, to show all tables:
USE mydatabase;
SHOW TABLES;
In this guide, we've walked through the process of opening a terminal in a Docker container running a MySQL server and executing SQL commands. Docker provides an easy and convenient way to run isolated instances of MySQL servers for testing or development purposes. Happy coding!