简体   繁体   中英

Remote accessing mysql server running on docker container

How to access the MySQL server running on a Docker container in a remote machine.

Here is my dockerfile:

MAINTAINER debu_bbsr@yahoo.com
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server \
 && sed -i "s/127.0.0.1/0.0.0.0/g" /etc/mysql/mysql.conf.d/mysqld.cnf \
 && mkdir /var/run/mysqld \
 && chown -R mysql:mysql /var/run/mysqld

VOLUME ["/var/lib/mysql"]

EXPOSE 3306

CMD ["mysqld_safe"]

I created an image:

sudo docker build -t deb_mysql_image .

Run the Docker container with the above image:

sudo docker run -i -t -d -p 3306:3306 --name mysql_deb_container deb_mysql_image

Enter into the MySQL container:

`k8smaster@k8smaster:~/debashish$ sudo docker exec -it mysql_deb_container mysql`

Create different users and database:

mysql> create user debashish identified by 'debashish';
mysql> create user debmysql identified by 'debmysql';
mysql> create database debdb;
mysql> use debdb;

Grant privileges to the users and create a table:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'debashish' WITH GRANT OPTION;  



CREATE TABLE debtbl1 (name VARCHAR(20), address VARCHAR(50));

Populate the table:

insert into debtbl1 values('Debashish', 'Shanghai');
insert into debtbl1 values('Debu', 'Livingston, Shanghai');

Now access the contents of the above MySQL table from a remote machine with the MySQL client:

k8snode1@k8snode1:~$ mysql -u 'debashish' -p  -h 10.10.10.2 -P 3306 -D debdb
Enter password

"Sometimes" I encounter the issue -

ERROR 1045 (28000): Access denied for user

Anything am I missing to make it a robust system so I dont encounter "sometimes" the above error.

Most likely your user doesn't have permissions to access from that server, either grant privileges for that specific server or globally.

Run:

GRANT ALL PRIVILEGES ON *.* TO 'debashish'@'%' WITH GRANT OPTION; 
FLUSH PRIVILEGES;

The issue was that - whenever a Pod was restarted, all the privileges assigned to the Mysql DB also gets erased.

Hence the solution was to - write a shell script that will be:

    1.  Executed when the Pod is started/scaled-in/container is started.
    2.  The shell script automatically creates the database and users.
    3.  Shell script then grants permission to the users for the DB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM