> ## Documentation Index
> Fetch the complete documentation index at: https://docs.minimus.io/llms.txt
> Use this file to discover all available pages before exploring further.

# MariaDB TLS Tutorial

> A guide to setting up MariaDB and testing that it accepts TLS connections, enforces authentication, and allows secure read/write operations from a test client

The following guide will help you deploy the Minimus MariaDB image with self-signed, locally issued certificates to help you get started. Run the code to try it for yourself.

<Info>
  For production purposes, we recommend using publicly trusted certificates issued by a Certificate Authority (CA).
</Info>

## Components

* **MariaDB image built by Minimus**: MariaDB container configured with the secure configuration for client authentication.
* Dynamic certificate generation via OpenSSL:
  * **certgen.sh script**: Shell script that generates a custom CA, server, and client certificates using OpenSSL.
  * **minidebug image**: A Minimus dev toolkit that provides a shell, OpenSSL, and other utilities used to generate the certificates.

## What this guide demonstrates

* TLS handshake validation
* Server/client certificate trust
* Basic auth and MariaDB operations
* Image compatibility

## Directory Structure

```bash theme={null}
.
├── certgen.sh             # Certificate generation script
├── create-certs.yml       # Compose file to run certgen container
└── docker-compose.yml     # Compose file to run MariaDB
```

## Deploy MariaDB with TLS certificates

### Prerequisite: Authenticate to the Minimus Registry

Run the docker login command to authenticate to the Minimus registry:

```shellscript theme={null}
echo "{token}" | docker login reg.mini.dev -u minimus --password-stdin
```

### Step 1: Generate TLS certificates

<Steps>
  <Step title="Save script that generates TLS certificates">
    Save the following script to a file named `certgen.sh`. The script is used to generate the TLS certificates and store them in a `certs` folder on the host.

    ```bash certgen.sh expandable theme={null}
    #!/bin/sh
    # Company: Minimus

    set -e
    cd /certs

    cat > openssl.cnf <<EOF
    [req]
    distinguished_name = req_distinguished_name
    prompt = no

    [req_distinguished_name]
    CN = mariadb

    [v3_req]
    keyUsage = keyEncipherment, dataEncipherment
    extendedKeyUsage = serverAuth, clientAuth
    subjectAltName = @alt_names

    [v3_client]
    keyUsage = digitalSignature
    extendedKeyUsage = clientAuth
    subjectAltName = @alt_names

    [v3_ca]
    subjectKeyIdentifier = hash
    authorityKeyIdentifier = keyid:always,issuer
    basicConstraints = critical, CA:true
    keyUsage = critical, keyCertSign, cRLSign

    [alt_names]
    DNS.1 = mariadb
    DNS.2 = localhost
    IP.1 = 172.0.0.1
    IP.1 = 192.168.60.0
    IP.1 = 192.168.60.2
    IP.1 = 192.168.60.3
    EOF

    openssl genrsa -out ca-key.pem 2048
    openssl req -x509 -new -nodes -key ca-key.pem -sha256 -days 365 -out ca.pem \
      -subj "/CN=MariaDB Test CA" -extensions v3_ca -config openssl.cnf

    openssl genrsa -out server-key.pem 2048
    openssl req -new -key server-key.pem -out server.csr -config openssl.cnf -extensions v3_req
    openssl x509 -req -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \
      -out server-cert.pem -days 365 -sha256 -extfile openssl.cnf -extensions v3_req

    openssl genrsa -out client-key.pem 2048
    openssl req -new -key client-key.pem -out client.csr -subj "/CN=root"
    openssl x509 -req -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \
      -out client-cert.pem -days 365 -sha256 -extfile openssl.cnf -extensions v3_client

    chmod 644 *.pem
    chown -R 1000:1000 /certs/*.pem || true
    echo "[SUCCESS] Certificates generated."
    ```
  </Step>

  <Step title="Save Docker Compose configuration">
    Save the following YAML file to run with Docker Compose. It uses the [**Minimus minidebug image**](https://images.minimus.io/gallery/images/minidebug/quick-start?__hstc=180987128.11065ee83c8bdcec1851176c12d849d3.1762436227738.1762436227738.1762436227738.1&__hssc=180987128.1.1762436227739&__hsfp=2666866004) to generate the certificates with the `certgen.sh` shell script. Minidebug is a Minimus dev toolkit that provides a shell, OpenSSL, and other utilities. The certificates will be persisted in the `certs` volume on the host.

    ```yaml create-certs.yml theme={null}
    services:
      certgen:
        image: reg.mini.dev/minidebug:latest
        container_name: mariadb_certgen
        volumes:
        - ./certs:/certs 
        - ./certgen.sh:/certgen.sh:ro
        entrypoint:
        - /bin/sh
        - /certgen.sh
        network_mode: none
    ```
  </Step>

  <Step title="Generate certificates">
    Run the following to generate the certificates:

    ```shellscript theme={null}
    docker compose -f create-certs.yml up
    ```
  </Step>
</Steps>

Congrats! You have just generated the following self-signed certificates:

* CA certificate (`ca.pem`)
* Server certificates (`server-cert.pem`, `server-key.pem`)
* Client certificates for `testuser` (`client-cert.pem`, `client-key.pem`, `client.csr`)

The permissions for all .pem certificates are set to `644` and owned by UID `1000`. Certificate permissions are adjusted to support non-root containers. In the next steps, you will mount these certificates into the MariaDB container.

### Step 2: Deploy MariaDB server

<Steps>
  <Step title="Save Docker Compose script">
    Save the following Docker Compose script to a file named `docker-compose.yml`. This script sets up the MariaDB service with a healthcheck, mounts a volume with the certificates, and maps port 3307 on the host to port 3306 on the container.

    ```yaml docker-compose.yml expandable theme={null}
    services:
      mariadb:
        image: reg.mini.dev/mariadb
        container_name: mariadb-1
        environment:
          MARIADB_ROOT_PASSWORD: rootpass
        ports:
        - 3307:3306
        volumes:
        - ./certs:/certs:ro
        command:
        - --ssl-ca=/certs/ca.pem
        - --ssl-cert=/certs/server-cert.pem
        - --ssl-key=/certs/server-key.pem
        - --require_secure_transport=ON
        healthcheck:
          test:
          - CMD
          - mariadb-admin
          - ping
          - -prootpass
          interval: 5s
          retries: 10
    ```
  </Step>

  <Step title="Run MariaDB">
    Start the MariaDB container in detached mode:

    ```shellscript theme={null}
    docker compose -f docker-compose.yml up -d
    ```
  </Step>
</Steps>

### Step 3: Test your MariaDB server

Connect to your database to test its connectivity.

First, make sure you are in the right folder, where the certs are available:

```typescript theme={null}
ls -l ./certs/
```

You can use mysql or mariadb-client to connect over TLS and run tests. For example, here are a few commands you can try out:

1. Connect to the db:

   <CodeGroup>
     ```bash Connect to DB theme={null}
     mysql -h 127.0.0.1 -P 3307 -u root -p \
       --ssl \
       --ssl-ca=./certs/ca.pem \
       --ssl-cert=./certs/client-cert.pem \
       --ssl-key=./certs/client-key.pem
     ```

     ```bash Expected response theme={null}
     Enter password: 
     # Type in the password set in the docker-compose.yml: `rootpass`
     Welcome to the MariaDB monitor.  Commands end with ; or \g.
     Your MariaDB connection id is 181
     Server version: 12.1.2-MariaDB MariaDB Server
     Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
     Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
     MariaDB [(none)]> 
     ```
   </CodeGroup>
2. Create and list databases:

   <CodeGroup>
     ```shellscript Create and list databases theme={null}
     CREATE DATABASE my_new_db; 
     SHOW DATABASES;
     ```

     ```bash Example response theme={null}
     Query OK, 1 row affected (0.001 sec)
     MariaDB [(none)]> SHOW DATABASES;
     +--------------------+
     | Database           |
     +--------------------+
     | information_schema |
     | my_new_db          |
     | mysql              |
     | new_db             |
     | performance_schema |
     | sys                |
     +--------------------+
     6 rows in set (0.001 sec)
     ```
   </CodeGroup>
3. Show server version:

   <CodeGroup>
     ```bash Show server version theme={null}
     SELECT version();
     ```

     ```Example response theme={null}
     +----------------+
     | version()      |
     +----------------+
     | 12.1.2-MariaDB |
     +----------------+
     1 row in set (0.001 sec)
     ```
   </CodeGroup>
4. Check that TLS is active:
   <CodeGroup>
     ```bash Check TLS theme={null}
     SHOW VARIABLES LIKE 'have_ssl';
     SHOW STATUS LIKE 'Ssl_cipher';
     SHOW STATUS LIKE 'Ssl_version';
     ```
   </CodeGroup>
