Create users for the mysql container of docker

Keywords: MySQL Docker Database SQL

Environmental Science

  • macOS 10.13.3

  • docker 17.12.0-ce

  • mysql container information

CONTAINER ID: 478bbac9137b
IMAGE: mysql:5.7.21


Currently, you use the MySQL container of docker to use mysql. As long as you run the container, you can use the local terminal connection and root login.

docker start 478bbac9137b
mysql -h -P 3306 -u root -p

Create new user

To prevent SQL injection attacks, set up a special user whose permission is limited to operating a database godb

CREATE USER 'schwarzeni'@'localhost' IDENTIFIED BY 'schwarzeni';
GRANT ALL PRIVILEGES ON  godb.* TO 'schwarzeni'@'localhost';

To see if it was created successfully:

select User, Host from mysql.user;
| User          | Host      |
| root          | %         |
| schwarzeni    | localhost |
| mysql.session | localhost |
| mysql.sys     | localhost |
| root          | localhost |


Try to log in locally

mysql -h -P 3306 -u schwarzeni -p

But it's wrong

ERROR 1045 (28000): Access denied for user 'schwarzeni'@'' (using password: YES)


localhost can only log in from within the container, that is:

docker exec -it 478bbac9137b bash

Then execute the login command and test

mysql -u schwarzeni -p


| Database           |
| information_schema |
| godb               |

So why can root access it on the local terminal? There is such a line when viewing mysql users

| User          | Host      |
| root          | %         |

The% mark of the Host matches the name of any Host, so can schwarzeni users

RENAME USER 'schwarzeni'@'localhost' TO 'schwarzeni'@'%';

In this way, you can access it locally, or create a user for the Host for

Reference link

Host '' is not allowed to connect to this MySQL server #275

Posted by Randwulf on Fri, 01 May 2020 19:03:19 -0700