Yeah, I wanted to do one of those for a long time 😁
So, we have to stay at home for the moment, I decided to make a “walkthrough” about something I used sometimes and I couldn’t remember all the commands. So, let’s build our MySQL database within a Docker container 🐳 !
I will be using the
mysql image from the Docker hub.
docker pull mysql
For further details, you can read the official documentation for the image on Docker hub. I will just go through the basic steps I use.
docker run --name my_container -e MYSQL_ROOT_PASSWORD=toor -d mysql:latest
--name: setup a name for our container
-e: setup environment variables
MYSQL_ROOT_PASSWORD: need explainations ?
-d: run in deamon mode
mysql:latest: use the
mysqlimage in the latest version
Once the container is running in background, we have to connect to it :
docker exec -it my_container /bin/bash
Here, we connect to the running container and pop a shell in interactive mode. We have to connect to the database :
mysql -uroot -ptoor
Now we can start to use SQL commands for our database.
CREATE DATABASE my_db;
CREATE TABLE compotes (id INT, name TEXT, note INT);
We want now to add some data in our table :
INSERT INTO compotes (id, name, note) VALUES (0, "Apple", 3);
Oh no, I f’cked up my data ! Apple & banana is not that tasty !
UPDATE compotes SET (note=4) WHERE id=1;
So drunk I added apple & apple in my table sight
DELETE FROM compotes WHERE name="Apple & apple";
OK, we are good.
I want to see my beautiful compotes now !
SELECT * FROM compotes;
We don’t want to re-type all the database when building a new container !
SQL scripts are cool for that :
And execute the script on the running container :
docker exec -i my_container sh -c 'exec mysql -uroot -ptoor' < populate.sql