Skip to content

Sql · Technical

MySQL Tutorial with Docker: Quick Setup Guide

Thanks to Docker, we can start MySQL in a container effortlessly and cleanly, isolating and controlling its resources

MySQL with Docker lets you spin up a relational database in seconds, with no local installation, cleanly isolated from your operating system. The essential command is: docker run --name mysql-dev -e MYSQL_ROOT_PASSWORD=root -p 3306:3306 -d mysql:8. This guide takes you from your first docker run to setting up users, permissions and data persistence, and covers the most common errors.

By the end of this guide you will have MySQL 8 running in Docker in under 5 minutes, ready to connect from DBeaver or any SQL client. All you need is Docker installed.

Why Use MySQL with Docker for Development?

Spinning up a database with Docker is the fastest way to have a programming environment ready to start coding on a home PC, without performing installations that leave remnants of files and configurations throughout the hard drive, greatly simplifying development and production environments. What is more, at Arteco we are container experts and can help you optimise your infrastructure.

How to Spin Up a MySQL Container Step by Step

And how is it done? In short, Docker is an open-source platform in the form of a virtual machine that manages and runs containers that package applications. Let's look at the details...

If you need to install Docker first, see our Docker tutorial.

Requirements for MySQL with Docker

If you are a Windows or Mac user, you need to have Docker Desktop installed on your PC or laptop, and it should have a certain capacity and power. Additionally, if you are a Windows user, you need to have the Professional version to install Docker. If not, visit the tutorial on installing Ubuntu, the best free and open-source operating system for programming. If you are an Ubuntu or Debian user, make sure you have Docker Compose on your system, as explained in the Docker installation tutorial.

Install MySQL with Docker

Starting a MySQL database with Docker couldn't be simpler. Just take the template of the Docker Compose configuration file provided below and invoke the command that will handle the entire process.

services:
  mysql:
    image: 'mysql:8'
    restart: always
    volumes:
      - './mysql_data:​/var/lib/mysql'
    environment:
      - MYSQL_ROOT_PASSWORD=secure_pass_here
    ports:
      - '3306:3306'

Save the file locally with the name docker-compose.yml in a directory named <home_user>/docker/mysql if you are on Unix, or <home_user>\docker\mysql if you are on Windows.

Configuring Persistence and Volumes in Docker

The configuration saves the data permanently in the ./mysql_data subdirectory; otherwise, the hosted databases would be lost every time the container restarts. Then, open a command terminal in the same directory as the file and run:

Note: If you use Docker Desktop 3.0+ or Docker Engine 23+, the command is docker compose (without a hyphen). The docker-compose command belongs to Compose V1, deprecated since 2023.

docker compose up -d

The system will first download the image from the public Docker repositories when it sees that it's not available locally, and then it will proceed to start and open the port specified in the configuration file. The -d option instructs Docker to run the service in the background.

From that point, use your preferred graphical interface to connect to the database. If you don't have one, you can get the free and multi-database client DBeaver.

Verify that the MySQL service is active

To verify that the service is active and the container is running normally, try running the following docker command that shows the running containers:

docker ps

You should see at least one entry corresponding to the active MySQL container, as shown below:

CONTAINER ID  IMAGE    COMMAND                 CREATED       STATUS       PORTS                               NAMES
327fd50443a7  mysql:8  "docker-entrypoint.s…"  29 hours ago  Up 6 hours   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql-mysql-1

If so, you can proceed with the rest of the activities, as mentioned in the previous text fragment, the container is running (status up) and listening on port 3306.

Need MySQL, PostgreSQL or Redis in production with high availability? At Arteco Consulting we design robust database architectures for Java/Spring Boot applications. Free consultation →

Connect MySQL with DBeaver

DBeaver SQL client connection screen for MySQL

If you have the SQL client DBeaver, once the container is running, you can connect with this multi-platform client by entering the following information:

Select new connection for MySQL 8+
Server host: localhost
Port: 3306
User name: root
Password: secure_pass_here

Next, click "Test Connection," and if everything goes well, click "Finish." From that moment on, the SQL graphical client can establish a connection with the container as long as it is running.

If you don't have much experience in managing databases like MySQL, we recommend reading the SQL tutorial for beginners.

Create MySQL User

Creating a user, other than the system administrator (root), is an important step, as it ensures that if we make a mistake executing SQL statements or if the application behaves unexpectedly, the impact will be limited to the scope of this user. Therefore, it's usually recommended to create a separate user for each database managed by the MySQL system. This way, all applications can operate independently without interfering with each other. This approach is highly recommended.

To create a user in MySQL, we need to know the username, password, and the IP address from which access will be allowed (or if it should be open from any address). Once we have these parameters clear, we'll open a connection using our preferred method and execute the following statement:

create user 'pepito'@'%' identified by 'pepitoPass';

The '%' character indicates that the 'pepito' user can connect from any IP address. If not, the '%' should be replaced with the corresponding IP address, keeping the quotes, or 'localhost' can be used as the host, allowing only local connections.

Change Password in MySQL

To change the password of a user in MySQL, we need to know which user we're referring to and from where they will be connecting, or from where it's allowed to connect. The user@host tuple is necessary to identify the line that needs to be modified.

ALTER USER 'pepito'@'%' IDENTIFIED BY 'securePepitoPass';

This statement assumes that the user previously had access from any internet address.

Delete a User in MySQL

To delete a user, once again we need the user-host pair. The operation cannot be undone; however, if a mistake is made, the user can be recreated. If done in this manner, neither the database nor the permissions associated with it would be affected.

drop user 'pepito'@'%';

Create MySQL Database

Creating a database in MySQL is one of the simplest operations to perform; it only requires the name of the database:

create database pepito_app;

Grant Permissions to a User in MySQL

Once the user and the database are created within the container running the SQL management system, the next step is to grant permissions to the user on that database. There is a wide range of permissions that users can have, allowing precise control over what each user can and cannot do. This granularity provides a high level of control and security over the stored data. For example, some commonly used permissions are:

  • ALL: Grants all permissions on the database
  • ALTER: Allows modification of tables, sequences, etc...
  • CREATE: Allows creation of tables, sequences, etc...
  • DROP: Allows deletion of tables, sequences, etc...
  • DELETE: Allows deletion of records in tables
  • INSERT: Allows insertion of records into tables
  • UPDATE: Allows updating records in tables
  • SELECT: Allows querying tables, sequences, etc...

In most cases, if we have one user per database, granting the ALL permission will be sufficient, or at least the necessary permissions to manage the records in the database. However, to grant permissions to a user on a database, we should write the following SQL statement:

grant all privileges on pepito_app.* to 'pepito'@'%';
flush privileges;

These two statements first grant all permissions on all objects (.*) in the pepito_app database, and then update the MySQL caches to reload the permissions configuration. Permissions are cached to speed up access resolution without having to read the configuration tables every time.

Revoke Permissions from a User in MySQL

Revoking permissions from a user is done similarly to granting access, but in this case, the revoke keyword is used as follows:

revoke insert on pepito_app.* from 'pepito'@'%';

Remember that after each privilege change, the cache should be updated with:

flush privileges;

Delete MySQL Database

If creation is one of the simplest operations to perform, deletion will be similar:

drop database pepito_app;

All tables, sequences, indexes, and data in the database will be permanently and irrevocably deleted from the management system. Make sure you enter the correct name of the database!

Common Problems

Port 3306 already in use

If you see the error Bind for 0.0.0.0:3306 failed, another service is using the port. Your options:

  • Stop the conflicting service: sudo systemctl stop mysql
  • Change the port in the compose file: - '3307:3306' (and connect your client to port 3307)

MySQL 8: authentication error with older clients

MySQL 8 uses caching_sha2_password by default. If your client or driver does not support it, add this to the service in the compose file:

command: --default-authentication-plugin=mysql_native_password

Data lost when the container restarts

If your data disappears after a restart, check that the ./mysql_data volume exists and is writable. On a Mac with Apple Silicon, you may need an absolute path rather than a relative one.

Conclusions

As we have learned, if you want to start programming quickly and efficiently without dealing with complicated installations, Docker is the solution. Setting up a database with Docker allows you to have a programming environment ready in minutes, without worrying about leaving traces of files and configurations on your hard drive. Visit Arteco consulting SL and discover this and much more content related to the world of web programming.


Bringing This Technology to Production

Need help putting this architecture into practice in your company? At Arteco Consulting we specialise in custom software development with Java, Spring Boot, Docker and cloud ecosystems. We design robust, scalable and secure solutions. Get in touch and implement it properly!

Running MySQL in your company and need it to scale? At Arteco we design production database architectures with high availability and automated backups. Talk to a specialist →

Ramón Arnau Gómez

Ramón Arnau Gómez

Director de Arteco

Programador Java desde 2003. Ingeniero Informático (UIB), Máster en Tecnologías de la Información (UIB), Máster en Administración y Dirección de Empresas (UAX). Arquitecto Java

More articles by Ramón