Docker Community Forums

Share and learn in the Docker community.

Run and connect to MySQL in one step using docker run

you can run and connect to mysql container in one line command this way:

docker run --name=mk-mysql -p3306:3306 -e MYSQL_ROOT_PASSWORD=my-secret-pw -it mysql/mysql-server:8.0 mysqlsh

I think that could be available for older versions of MySQL but I am unable to do such one liner. (No compose, sh or similar workarounds, just docker run command)

Any hint would be much appreciated

that is a very confusing command line. you’re trying to run mysqlsh from the command line within the container itself but it looks like it’s constructed wrong.

could be all kinds of reasons. it’s missing the direct path to mysqlsh, the image name should be at the end of the command, etc.

Step 1: Pull the MySQL Docker Image

  1. Start by pulling the appropriate Docker image for MySQL. You can download a specific version or opt for the latest release as seen in the following command:

docker pull mysql/mysql-server:latest
If you want a particular version of MySQL, replace latest with the version number.

  1. Verify the image is now stored locally by listing the downloaded Docker images:

docker images
The output should include mysql/mysql-server among the listed images.

example Docker image on your system for deploying a MySQL Docker container
Step 2: Deploy the MySQL Container

  1. Once you have the image, move on to deploying a new MySQL container with:

docker run --name=[container_name] -d mysql/mysql-server:latest
Replace [container_name] with the name of your choice. If you do not provide a name, Docker generates a random one.
The -d option instructs Docker to run the container as a service in the background.
In the command above, we used the latest version tag. This may differ according to the image you downloaded.
2. Then, check to see if the MySQL container is running:

docker ps
You should see the newly created container listed in the output. It includes container details, one being the status of this virtual environment. The status changes from health: starting to healthy, once the setup is complete.

Command to deploy a MySQL Docker container and verify MySQL container is running
Step 3: Connect to the MySQL Docker Container

  1. Before you can connect the MySQL server container with the host, you need to make sure the MySQL client package is installed:

apt-get install mysql-client
2. Then, start a MySQL client inside the container by typing:

docker exec -it [container_name] mysql -uroot -p
3. Provide the root password, when prompted. With that, you have connected the MySQL client to the server.

  1. Finally, change the server root password to protect your information:

mysql> ALTER USER ‘root’@‘localhost’ IDENTIFIED BY ‘[newpassword]’;
Replace [newpassword] with a strong password of your choice.