• /
  • /

Run MySQL in Docker Compose: Setup, Storage, and Restore

Run MySQL 8.4 in Docker Compose with the complete compose.yaml below. Connect from your host at 127.0.0.1:13306 or from an app on the same Compose network at mysql:3306. You’ll check that a named volume keeps your data when you recreate the container, then restore a test row from a SQL backup.
You need Docker with the Compose plugin, a POSIX-style shell, and OpenSSL. The MySQL image includes a client for checking the running server. For the host connection and backup steps, install the MySQL 8.4 mysql and mysqldump clients on your computer.

Create the project files

Start a new local project. Keep the same directory, terminal, and Compose project name throughout the example.
mkdir -m 700 mysql-compose-lab && cd mysql-compose-lab
After that succeeds, generate separate passwords for the application and database administrator. These commands write them directly to private files. The shell setting set -C prevents later redirects from replacing an existing file.
umask 077
set -C
openssl rand -hex 24 > mysql-app-password.txt
openssl rand -hex 24 > mysql-root-password.txt
Save this as .gitignore in the new directory. It keeps both credentials and the SQL backup from being added to Git.
mysql-app-password.txt
mysql-root-password.txt
*.sql
Save the following as mysql-demo.cnf. A value of 60 makes it easy to check whether the server actually loads the file.
[mysqld]
max_connections=60
Give the MySQL process read access to this configuration file. Leave the password files private.
chmod 644 mysql-demo.cnf
Save the full service definition as compose.yaml alongside those files.
services:
  mysql:
    image: mysql:8.4
    environment:
      MYSQL_ROOT_HOST: localhost
      MYSQL_ROOT_PASSWORD_FILE: /run/secrets/mysql_root_password
      MYSQL_DATABASE: appdb
      MYSQL_USER: app
      MYSQL_PASSWORD_FILE: /run/secrets/mysql_app_password
    secrets:
      - mysql_root_password
      - mysql_app_password
    ports:
      - "127.0.0.1:13306:3306"
    volumes:
      - mysql_data:/var/lib/mysql
      - ./mysql-demo.cnf:/etc/mysql/conf.d/mysql-demo.cnf:ro
    mem_limit: 1g
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "--silent"]
      interval: 5s
      timeout: 3s
      retries: 20
      start_period: 20s

secrets:
  mysql_root_password:
    file: ./mysql-root-password.txt
  mysql_app_password:
    file: ./mysql-app-password.txt

volumes:
  mysql_data:
On the first start with an empty data volume, the image creates appdb and the app account. The _FILE settings tell the image where to read each password. Root access is local to the MySQL container in this example. Once the volume contains a database, editing the password files does not reset the existing MySQL accounts. Official MySQL image documentation

Start MySQL and check the application login

From the project directory, start the service and wait for its health check.
docker compose up -d --wait
The check runs mysqladmin ping over TCP inside the container. It can succeed even if MySQL refuses the login, because an access-denied response still means the server answered. Check that the application account can open its database with an authenticated query. MySQL’s mysqladmin reference
docker compose exec mysql mysql --user=app --password appdb \
  -e 'SELECT DATABASE(), CURRENT_USER()'
At the hidden password prompt, enter the value from mysql-app-password.txt. Open that local file in your editor when you need the password. The query should return appdb and app@%. If startup fails, use docker compose ps and docker compose logs mysql to see whether the service started and which error MySQL reported.

Connect from your host or application

The example starts one service, MySQL. The app container in the diagram represents your own application if you add it to the same Compose network.
The host connects at 127.0.0.1:13306 and an app on the Compose network connects at mysql:3306. The mysql_data volume holds the data. A separate read-only mount supplies mysql-demo.cnf.
MySQL in Docker Compose: connections, data volume, and configuration mount.
Docker publishes port 13306 on your computer’s loopback interface and forwards it to port 3306 in the container. A neighboring service can resolve the database by its Compose service name, mysql. Inside an application container, localhost points back to that application container. Docker Compose networking
Try the host route with the MySQL client on your computer. Use the app password again.
mysql --host=127.0.0.1 --port=13306 --user=app --password appdb \
  -e 'SELECT DATABASE(), @@port'
The server reports appdb and its internal port, 3306. Keep 13306 in the host client’s connection settings. How to identify the MySQL port
If you want to monitor this instance with a Releem Agent container, connect the agent to a network that can reach MySQL and give it a dedicated monitoring account. Install Releem for MySQL on Docker

Recreate the container and read the same row

Create a small InnoDB table and put one note in it. Run this once against the new appdb.
docker compose exec mysql mysql --user=app --password appdb -e "
  CREATE TABLE notes (id INT PRIMARY KEY, body VARCHAR(80) NOT NULL) ENGINE=InnoDB;
  INSERT INTO notes VALUES (1, 'saved in mysql_data');
  SELECT id, body FROM notes WHERE id = 1;"
You should see ID 1 and the text saved in mysql_data. The named volume mysql_data holds MySQL’s data directory at /var/lib/mysql. Run plain down to remove the container while keeping that volume. Adding --volumes would also remove the project’s named volume and its data. Docker Compose down reference
docker compose down
docker compose up -d --wait
Read the note through the new container.
docker compose exec mysql mysql --user=app --password appdb \
  -e 'SELECT id, body FROM notes WHERE id = 1'
If row 1 is missing, check the current Compose project name and its volume before writing anything to the new database. A new project name can select a different volume. A successful read shows that the original volume survived container recreation. Losing that volume is a different recovery problem.

Check the MySQL setting and the container memory limit

The bind mount exposes mysql-demo.cnf inside the container as a read-only configuration file. Query MySQL to see whether it loaded the connection limit.
docker compose exec mysql mysql --user=app --password appdb \
  -e "SHOW GLOBAL VARIABLES LIKE 'max_connections'"
The expected value is 60. For the memory limit, ask Docker for the registered limit in bytes on this service’s container.
docker inspect --format '{{.HostConfig.Memory}}' "$(docker compose ps -q mysql)"
1073741824 bytes is 1 GiB, the 1g configured by mem_limit. It caps the container’s memory. MySQL’s current memory use and the memory your own workload needs are separate measurements.

Back up MySQL and restore the note from a file

Use the host’s mysqldump client to write a logical backup of appdb outside the container. Run this in the same private directory and shell. app-db.sql must be a new filename. The example takes a consistent snapshot of the InnoDB rows, so leave table definitions unchanged during the export. MySQL mysqldump reference
mysqldump --host=127.0.0.1 --port=13306 --user=app --password \
  --single-transaction --quick --no-tablespaces --set-gtid-purged=OFF \
  appdb > app-db.sql
Continue only after the export succeeds. A failed export can leave a partial file. If the shell rejected an existing filename, the old file is still there. For a retry, choose an unused name such as app-db-retry.sql. Use that name both after > in the export above and after < in the import below. Correct the cause and repeat the export before continuing.
For this one-table drill, create a second, empty database called restorecheck on the same local server. First check that the host client and the container’s local administrator connection reach the same instance. Enter the app password for the first command and the root password from mysql-root-password.txt for the second. Compare the two UUIDs and stop if they differ.
mysql --host=127.0.0.1 --port=13306 --user=app --password appdb -e 'SELECT @@server_uuid'
docker compose exec mysql mysql --user=root --password -e 'SELECT @@server_uuid'
The first command below creates the target and gives app the privileges used by this dump. The && starts the import only if both the creation and the grant succeed. During the import, the mysql client stops on the first SQL error when you run it without --force.
docker compose exec mysql mysql --user=root --password -e "
  CREATE DATABASE restorecheck;
  GRANT SELECT, CREATE, DROP, INSERT, ALTER, LOCK TABLES ON restorecheck.* TO 'app'@'%';" &&
mysql --host=127.0.0.1 --port=13306 --user=app --password restorecheck < app-db.sql
Check the restored table by querying restorecheck explicitly. After a partial import, fix the error and retry in a new empty database.
mysql --host=127.0.0.1 --port=13306 --user=app --password restorecheck \
  -e 'SELECT id, body FROM notes WHERE id = 1'
In Releem’s test with MySQL 8.4.11, Docker Engine 29.8.0, and Compose 5.5.1, row 1 contained saved in mysql_data both after container recreation and after restoring the file into restorecheck.
Reading the note in restorecheck verifies that the SQL file can rebuild this table and its row. Both schemas still share the same volume. Keep a backup on another system if you need to recover from losing the host. For your own project, choose a record you can recognize, restore the backup to a fresh test database, and check that record there.