MySQL Authentication in Docker Containers: Step-by-Step Guide
In this article, we will discuss how to set up and configure MySQL authentication in Docker containers. We will cover the following topics:
- Creating a Docker container with a MySQL image
- Creating and configuring databases and users
- Connecting to the databases using the created users
Creating a Docker Container with a MySQL Image
The first step is to create a Docker container running the MySQL image. In this example, we will create a container named sql.container.
docker run --name sql.container -e MYSQL\_ROOT\_PASSWORD=mysecretpassword -d mysql
This command creates a new container named sql.container and runs it in the background. The -e MYSQL\_ROOT\_PASSWORD=mysecretpassword option sets the root password for the MySQL instance inside the container. Replace mysecretpassword with a secure password of your choice.
Creating and Configuring Databases and Users
Once the container is up and running, we can connect to the MySQL instance inside the container and create the databases and users.
docker exec -it sql.container mysql -u root -p
This command connects to the MySQL instance inside the container using the root user. You will be prompted to enter the root password that you set in the previous step.
Once connected, you can create the databases and users as follows:
CREATE DATABASE database1;
CREATE DATABASE database2;
GRANT ALL PRIVILEGES ON database1.* TO 'user1'@'%' IDENTIFIED BY 'user1password';
GRANT ALL PRIVILEGES ON database2.* TO 'user2'@'%' IDENTIFIED BY 'user2password';
This creates two databases named database1 and database2, and two users named user1 and user2. The GRANT statement gives all privileges on the respective databases to the corresponding users. Replace user1password and user2password with secure passwords of your choice.
Connecting to the Databases Using the Created Users
Now that the databases and users have been created, we can connect to them using the created users.
docker exec -it sql.container mysql -u user1 -p database1
This command connects to the database1 database using the user1 user. You will be prompted to enter the password for the user1 user.
You can repeat the above step for the user2 user and the database2 database.
- We have discussed how to create a Docker container running the MySQL image.
- We have covered how to create and configure databases and users in the MySQL instance inside the container.
- We have demonstrated how to connect to the databases using the created users.