Create a MySQL database in Docker Container (Linux) using CLI

This guide shows how to create a database using CLI on a Linux server with MySql running in a Docker container.

Use a terminal and connect to the server usign SSH. We will not go into this in detail.

$ ssh root@yourserver.io

To show the running instance of MySql use the following

[root@yourserver]# docker ps

This will show the running docker instances on the server

CONTAINER ID       ...   ...  ...  ...    PORTS                 NAMES
3998b8b25eed       ...   ...  ...  ...   0.0.0.0:8003->80/tcp  root_wordpress
241255e5e435       ...   ...  ...  ...   3306/tcp, 33060/tcp   root_db_1

Now that we know the ID of the container where MySql is running, we connect to the container:

[root@yourserver]# docker exec -it 241255e5e435 bash

This runs a shell in the docker container where we can now connect to the server using the command line.

root@241255e5e435:/# mysql -u root -p

Once logged into as root we can create a new database.

mysql> CREATE DATABASE new_database;

Use the next command to display the database next to the existing ones.

mysql> show databases;

Jump right into the database and select it to perform SQL operations into that database.

mysql> use new_database;

Next create a new user that will have access to the newly created database

CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'password';

NOTE: Be sure to change theuserto the username you need and password to a sufficiently secure password.

And grant the permission to the user

GRANT ALL PRIVILEGES ON new_database.* TO 'new_user'@'%';
GRANT ALL ON new_database.* to new_user@localhost IDENTIFIED BY 'password';

NOTE: Be sure to change theuser and password to the ones before

Test the access to the database by logging in as the created user and select the database, as shown in the commands above. Now, you know how to create a MySQL database from the command line.

Thomas Trügler Written by: