Reset the root password for MySQL in a Docker container

1. Stop the MySQL Docker container:

$ docker stop <container_name_or_id>

2. Remove the existing MySQL container:

$ docker rm <container_name_or_id>

This step is necessary because you cannot modify the root password directly in the existing container.

3. Create a new MySQL container with a mounted volume:

$ docker run -d \
- name mysql-container \
-e MYSQL_ROOT_PASSWORD=temporary_password \
-v /path/on/host:/var/lib/mysql \
mysql:latest

Replace /path/on/host with the path on your host machine where you want to store the MySQL data files.
This step creates a new MySQL container with a temporary password for the root user.

4. Access the MySQL container:

$ docker exec -it mysql-container mysql -uroot -p

You will be prompted to enter the temporary password. Use the one you specified in the MYSQL_ROOT_PASSWORD environment variable.

5. Change the root password:

$ ALTER  USER  'root'@'localhost' IDENTIFIED BY  'new_password';

Replace ‘new_password’ with your desired new password.

6. Exit the MySQL prompt:

$ exit;

7. Stop the MySQL container:

$ docker stop mysql-container

8. Remove the MySQL container:

$ docker rm mysql-container

9. Start a new MySQL container without the mounted volume:

$ docker run -d \
- name mysql-container \
-e MYSQL_ROOT_PASSWORD=new_password \
mysql:latest

This time, use the new password in the MYSQL_ROOT_PASSWORD environment variable.

Now you have successfully reset the root password for MySQL in a Docker container. The key steps involve creating a new container, accessing it, changing the password, and then starting a fresh container with the updated password. Using a mounted volume ensures that your MySQL data persists across container recreations.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics