Skip to lesson

Running MySQL in a container

ShopLite needs a real database, but installing MySQL by hand differs on every laptop and often clashes with one you already have. One docker run command gives everyone the same server.

docker run mysql:8.4: variables, volume and port

mysql:8.4 is the official MySQL image on the 8.4 long-term support (LTS) line. On its first start it creates a MySQL server, a database and an app user from the environment variables you pass.

Start ShopLite's database with four MYSQL_ variables, a named volume and a port mapping. The command is long, so read it line by line.

Example 1 · Start shoplite-db with a volume and port 3307

Runs in: a terminal with Docker installed

Terminal
docker volume create shoplite-datadocker run -d --name shoplite-db \  -e MYSQL_ROOT_PASSWORD='root-dev-pass' \  -e MYSQL_DATABASE=shoplite \  -e MYSQL_USER=shoplite \  -e MYSQL_PASSWORD='shoplite-dev-pass' \  -v shoplite-data:/var/lib/mysql \  -p 3307:3306 \  mysql:8.4docker ps --filter name=shoplite-db
Sample output (your IDs and times will differ)
shoplite-data
Unable to find image 'mysql:8.4' locally
8.4: Pulling from library/mysql
...
Status: Downloaded newer image for mysql:8.4
7c1e4b9a2f3d8e6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a7b6c5d4e3f2a
CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS         PORTS                                                    NAMES
7c1e4b9a2f3d   mysql:8.4   "docker-entrypoint.s…"   12 seconds ago   Up 11 seconds  0.0.0.0:3307->3306/tcp, [::]:3307->3306/tcp, 33060/tcp   shoplite-db

What this code does

  • The first run pulls mysql:8.4 once; docker run -d then prints the new container's ID and returns at once, while MySQL keeps starting in the background.
  • The PORTS column shows 0.0.0.0:3307->3306/tcp: port 3307 on every address of your laptop forwards to 3306 inside. 33060/tcp is MySQL's X Protocol port, exposed by the image but not published.
  • The passwords are in single quotes so the shell never changes characters such as $ or !. The Environment variables lesson showed how to keep them out of the command with an env file; the module project does that.

The image reads four variables: MYSQL_ROOT_PASSWORD (required), MYSQL_DATABASE (a database to create), and MYSQL_USER with MYSQL_PASSWORD (an app user who gets full rights on that database).

Two more flags make it useful. -v shoplite-data:/var/lib/mysql keeps the data in the named volume, so it survives docker rm. -p 3307:3306 publishes MySQL's port 3306 on port 3307 of your laptop, on purpose, because many students already run a local MySQL on 3306. Always pin the tag: mysql alone means latest, which can jump to a new major version on the next pull.

Fix the error

The container exits at once

docker logs shows this error. Pick the replacement for line 2.

A new volume, but no root password.

docker run -d --name shoplite-db \
-e MYSQL_DATABASE=shoplite \
mysql:8.4

Error

[ERROR] [Entrypoint]: Database is uninitialized and password option is not specified
    You need to specify one of the following as an environment variable:
    - MYSQL_ROOT_PASSWORD
In Windows PowerShell, end each continued line with a backtick (`) instead of a backslash, or write the whole command on one line.

Init scripts in /docker-entrypoint-initdb.d

/docker-entrypoint-initdb.d is the folder in the mysql image for init scripts, files ending in .sql or .sh. The image's start script (the entrypoint) runs them in alphabetical order, as root, once the database and user exist.

Mount a SQL file into the init folder and watch the log: the file runs on the first start, and not on the second.

Example 2 · An init script runs on the first start only

Runs in: a terminal with Docker installed

Terminal
mkdir -p db/initcat db/init/01-test-database.sqldocker run -d --name initdemo-db \  -e MYSQL_ROOT_PASSWORD='root-dev-pass' \  -e MYSQL_DATABASE=shoplite \  -e MYSQL_USER=shoplite \  -e MYSQL_PASSWORD='shoplite-dev-pass' \  -v initdemo-data:/var/lib/mysql \  -v "$PWD/db/init":/docker-entrypoint-initdb.d:ro \  -p 3308:3306 \  mysql:8.4docker logs initdemo-db 2>&1 | grep Entrypoint# second start on the SAME volume: remove the container, run the same command againdocker rm -f initdemo-dbdocker run -d --name initdemo-db ...same flags as above...docker logs initdemo-db 2>&1 | grep Entrypoint
Sample output
-- Runs once, on an empty volume, as root, after the shoplite user exists.
CREATE DATABASE IF NOT EXISTS shoplite_test;
GRANT ALL PRIVILEGES ON shoplite_test.* TO 'shoplite'@'%';

[Note] [Entrypoint]: Entrypoint script for MySQL Server 8.4.6-1.el9 started.
[Note] [Entrypoint]: Switching to dedicated user 'mysql'
[Note] [Entrypoint]: Entrypoint script for MySQL Server 8.4.6-1.el9 started.
[Note] [Entrypoint]: Initializing database files
[Note] [Entrypoint]: Database files initialized
[Note] [Entrypoint]: Starting temporary server
[Note] [Entrypoint]: Temporary server started.
[Note] [Entrypoint]: Creating database shoplite
[Note] [Entrypoint]: Creating user shoplite
[Note] [Entrypoint]: Giving user shoplite access to schema shoplite
[Note] [Entrypoint]: /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/01-test-database.sql
[Note] [Entrypoint]: Stopping temporary server
[Note] [Entrypoint]: Temporary server stopped
[Note] [Entrypoint]: MySQL init process done. Ready for start up.

(second start)
[Note] [Entrypoint]: Entrypoint script for MySQL Server 8.4.6-1.el9 started.
[Note] [Entrypoint]: Switching to dedicated user 'mysql'
[Note] [Entrypoint]: Entrypoint script for MySQL Server 8.4.6-1.el9 started.
(timestamps at the start of each line trimmed)

What this code does

  • The first run finds an empty volume, so the entrypoint initialises MySQL, creates shoplite and its user, and then runs 01-test-database.sql.
  • The second container uses the same volume initdemo-data, so the entrypoint goes straight to starting MySQL: no "Initializing", no "running" line. Clean up with docker rm -f initdemo-db and docker volume rm initdemo-data.
  • :ro mounts the folder read-only, and "$PWD/db/init" is the bind mount from the Volumes lesson (in PowerShell write ${PWD}/db/init).

The catch: all of this happens only when /var/lib/mysql is empty. On every later start, the entrypoint sees an existing database and skips the whole init step. It does not read the MYSQL_* variables again and does not run any init script, old or new.

For ShopLite the tables belong to Flyway, so init scripts are only for setup that Flyway does not do, such as an extra shoplite_test database for tests. Number the files (01-, 02-) to fix their order.

Predict the output

Does the init script run?

db/init/01-test-database.sql is mounted every time. Pick what happens.

Round 1 of 2

First start on a brand-new volume.

docker volume create shoplite-data
docker run -d --name shoplite-db -v shoplite-data:/var/lib/mysql ... mysql:8.4

Connecting from the host: mysql client, Workbench and JDBC

A JDBC URL is the address a Java program uses to reach a database, written jdbc:mysql://host:port/database. For ShopLite's container, seen from your laptop, it is jdbc:mysql://localhost:3307/shoplite.

From your laptop, the container is a MySQL server on 127.0.0.1, port 3307. Log in with the mysql client, then build the JDBC URL ShopLite needs.

Example 3 · Log in with the mysql client on port 3307

Runs in: a terminal with Docker installed

Terminal
mysql -h 127.0.0.1 -P 3307 -u shoplite -p shoplitemysql> SELECT DATABASE(), CURRENT_USER(), @@version;mysql> SHOW DATABASES;
Sample output
Enter password: *****************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Server version: 8.4.6 MySQL Community Server - GPL

mysql> SELECT DATABASE(), CURRENT_USER(), @@version;
+------------+----------------+-----------+
| DATABASE() | CURRENT_USER() | @@version |
+------------+----------------+-----------+
| shoplite   | shoplite@%     | 8.4.6     |
+------------+----------------+-----------+
1 row in set (0.00 sec)

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| performance_schema |
| shoplite           |
+--------------------+
3 rows in set (0.01 sec)

What this code does

  • -h 127.0.0.1 -P 3307 reaches the container through the port mapping; the final shoplite picks the default database.
  • CURRENT_USER() is shoplite@%: the image creates the app user for any host (%), which is why connections through Docker's network are allowed.
  • SHOW DATABASES lists only shoplite and the system schemas the user may see. The tables appear when Flyway runs in the module project.

Example 4 · Build and read a MySQL JDBC URL

JdbcUrlDemo.javaJava
import java.net.URI;
record DbAddress(String host, int port, String database) {
    String toJdbcUrl() {        return "jdbc:mysql://" + host + ":" + port + "/" + database;    }
    static DbAddress parse(String jdbcUrl) {        if (!jdbcUrl.startsWith("jdbc:mysql://")) {            throw new IllegalArgumentException("Not a MySQL JDBC URL: " + jdbcUrl);        }        URI uri = URI.create(jdbcUrl.substring("jdbc:".length()));        int port = uri.getPort() == -1 ? 3306 : uri.getPort();   // MySQL's default port        String database = uri.getPath().substring(1);             // "/shoplite" -> "shoplite"        return new DbAddress(uri.getHost(), port, database);    }}
public class JdbcUrlDemo {    public static void main(String[] args) {        DbAddress container = new DbAddress("localhost", 3307, "shoplite");        System.out.println("App on your laptop uses: " + container.toJdbcUrl());        System.out.println();
        String[] urls = {            "jdbc:mysql://localhost:3307/shoplite",            "jdbc:mysql://localhost/shoplite",            "jdbc:mysql://127.0.0.1:3307/shoplite?connectTimeout=5000"        };        for (String url : urls) {            DbAddress a = DbAddress.parse(url);            System.out.println(a.host() + " | port " + a.port() + " | database " + a.database());        }    }}
Output
App on your laptop uses: jdbc:mysql://localhost:3307/shoplite

localhost | port 3307 | database shoplite
localhost | port 3306 | database shoplite
127.0.0.1 | port 3307 | database shoplite

What this code does

  • A MySQL JDBC URL is jdbc:mysql://host:port/database. toJdbcUrl builds the one ShopLite needs for the container: host localhost, port 3307.
  • parse cuts off jdbc: and lets java.net.URI split the rest. When no port is given, getPort() returns -1 and MySQL's default 3306 is used, which is exactly the wrong port for our container.
  • The query part (?connectTimeout=5000) is not part of the path, so the database name stays shoplite.

Every client uses the same four facts: host, port, user and database. Use 127.0.0.1 rather than localhost with the mysql command line client. On Linux and macOS, mysql -h localhost tries a local socket file instead of TCP and never reaches the container. JDBC always uses TCP, so localhost is fine there.

Settings by client:

  • mysql client: mysql -h 127.0.0.1 -P 3307 -u shoplite -p shoplite (capital -P is the port).
  • MySQL Workbench: a new connection with Hostname 127.0.0.1, Port 3307, Username shoplite, Default Schema shoplite.
  • JDBC: jdbc:mysql://localhost:3307/shoplite, the value ShopLite reads from DB_URL.
  • No mysql client installed? The Shell into a container lesson runs the client inside the container instead.

Waiting for "ready for connections"

Ready for connections is the MySQL log line that says the server accepts connections. On a first start it appears twice: port: 0 is a temporary setup server, and port: 3306 is the real one.

docker run -d returns in a second, but MySQL needs 10 to 30 seconds on its first start. Watch the log, then wait in a loop.

Example 5 · Watch for ready for connections, then wait in a loop

Runs in: a terminal with Docker installed

Terminal
docker logs -f shoplite-db          # watch the start; press Ctrl+C to stop watchingdocker logs shoplite-db 2>&1 | grep "ready for connections"# or wait in a script until the real server answers over TCPuntil docker exec shoplite-db mysqladmin ping -h 127.0.0.1 --silent; do  echo "waiting for MySQL..."  sleep 2doneecho "MySQL is ready on localhost:3307"
Sample output
... Temporary server started.
... /usr/sbin/mysqld: ready for connections. Version: '8.4.6'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server - GPL.
... MySQL init process done. Ready for start up.
... X Plugin ready for sockets. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
... /usr/sbin/mysqld: ready for connections. Version: '8.4.6'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
^C

2026-10-16T08:12:10.317542Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.6'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server - GPL.
2026-10-16T08:12:15.103211Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.6'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.

waiting for MySQL...
waiting for MySQL...
MySQL is ready on localhost:3307

What this code does

  • The log shows the temporary server (port: 0) first and the real server (port: 3306) last; only the last line means the app can connect.
  • docker exec runs a command inside the running container; the next lesson covers it fully. mysqladmin ping -h 127.0.0.1 --silent exits with 0 as soon as the server answers over TCP and prints nothing while it waits.

Example 6 · A retry loop in Java: wait until a port opens

WaitForPortDemo.javaJava
import java.io.IOException;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.net.Socket;
public class WaitForPortDemo {
    static boolean isOpen(String host, int port) {        try (Socket socket = new Socket()) {            socket.connect(new InetSocketAddress(host, port), 500);   // give up after 500 ms            return true;        } catch (IOException e) {            return false;                                             // refused or timed out        }    }
    public static void main(String[] args) throws Exception {        int port;        try (ServerSocket probe = new ServerSocket(0)) {            port = probe.getLocalPort();        }
        ServerSocket fakeDatabase = null;        int maxAttempts = 10;        boolean ready = false;        for (int attempt = 1; attempt <= maxAttempts && !ready; attempt++) {            if (attempt == 3) {                fakeDatabase = new ServerSocket(port);                 // the "database" finishes starting                System.out.println("(the test database starts listening)");            }            ready = isOpen("127.0.0.1", port);            if (ready) {                System.out.println("Attempt " + attempt + ": port is open, connect now");            } else {                System.out.println("Attempt " + attempt + ": not ready, waiting 200 ms");                Thread.sleep(200);            }        }        if (fakeDatabase != null) {            fakeDatabase.close();        }        System.out.println(ready ? "Done" : "Gave up after " + maxAttempts + " attempts");    }}
Output
Attempt 1: not ready, waiting 200 ms
Attempt 2: not ready, waiting 200 ms
(the test database starts listening)
Attempt 3: port is open, connect now
Done

What this code does

  • isOpen tries a TCP connection with a 500 ms limit. A refused or timed-out connection means "not yet", so the loop sleeps and tries again instead of failing at once.
  • The program plays both sides: it finds a free port, keeps it closed for two attempts, then opens a ServerSocket on it, like MySQL finishing its start. A cap on attempts stops the loop from waiting forever.
  • Against a container this check can pass early, because Docker opens 3307 before MySQL listens. Real apps also retry the first real connection, which Spring Boot's connection pool does for you.

A Java app that connects too early fails, so wait until the second line, the one with port: 3306. In scripts, a loop is better than reading logs: mysqladmin ping -h 127.0.0.1 inside the container succeeds only when the real server answers over TCP.

Three ways to wait:

  • docker logs -f shoplite-db follows the log; MySQL writes it to stderr, so add 2>&1 before piping it to grep.
  • --health-cmd "mysqladmin ping -h 127.0.0.1 --silent" on docker run makes Docker run the check itself; docker ps then shows (healthy). The module project uses this.
  • A port check from the host is weaker: Docker itself listens on 3307 from the moment the container starts, so the port can look open before MySQL is.

Trace the code

A wait loop, step by step

Press next to follow the retry idea. The pretend database is ready on the 3rd try.

public class WaitDemo {
public static void main(String[] args) {
int attempt = 0;
boolean ready = false;
while (!ready) {
attempt++;
ready = attempt >= 3;
System.out.println("attempt " + attempt + (ready ? ": ready" : ": not ready"));
}
System.out.println("connect after " + attempt + " attempts");
}
}

Variables

attempt
0

Output

(nothing printed yet)

Line 3attempt starts at 0: nothing has tried to connect yet.

Step 1 of 13

Three errors: Access denied, Communications link failure, port in use

Access denied (ERROR 1045) means MySQL answered but rejected the user or password. After you change MYSQL_PASSWORD, the cause is almost always the volume, which still holds the old user with the old password.

Three errors cause most trouble with a MySQL container. Here is what each looks like, in the order students meet them.

Terminal
$ mysql -h 127.0.0.1 -P 3307 -u shoplite -pERROR 1045 (28000): Access denied for user 'shoplite'@'172.17.0.1' (using password: YES)$ ./mvnw spring-boot:run        # DB_URL still says localhost:3306, nothing listens therecom.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failureThe last packet sent successfully to the server was 0 milliseconds ago.The driver has not received any packets from the server.$ docker run -d --name shoplite-db ... -p 3306:3306 mysql:8.4     # a local MySQL owns 3306docker: Error response from daemon: ports are not available: exposing port TCP0.0.0.0:3306 -> 127.0.0.1:0: listen tcp 0.0.0.0:3306: bind: Only one usage of eachsocket address (protocol/network address/port) is normally permitted.

Fix it by logging in with the old password and running ALTER USER, or, in development only, by removing the container and the volume. Communications link failure comes from the JDBC driver when nothing answers on that host and port: the container is stopped, or DB_URL still says 3306. If a local MySQL runs on 3306, the wrong port does not fail at all; you silently reach the other server and see "Unknown database" or old data.

Port in use appears when the host port is taken. With another container it says port is already allocated; with a local MySQL service Windows says "Only one usage of each socket address" and Linux says address already in use. Change the host side of -p, for example to 3307.

Next step

Check your understanding

12 quick questions