DEV Community

Vuong
Vuong

Posted on

Allow SSH tunnelling for Docker MySQL

MySQL Docker images usually come without SSH connection. It's fine for apps to connect within an internal network, but need additional work to have SSH connection to access it remotely.

Overview

Here is how it looks for this setup

SSH Connection to Docker MySQL

Let's have some code

  1. We need a Dockerfile to inherit from original Dockerfile
FROM mysql:8.0-debian # Install SSH server RUN apt-get update && apt-get install -y openssh-server && \  mkdir /var/run/sshd && \  echo 'root:yourpassword' | chpasswd && \  sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config && \  sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config # Ensure SSH service starts properly RUN echo '/usr/sbin/sshd' >> /etc/bash.bashrc # Expose SSH and MariaDB ports EXPOSE 22 3306 # Copy a script to start both SSH and MariaDB COPY start.sh /start.sh RUN chmod +x /start.sh # Use the custom start script as the entry point ENTRYPOINT ["/start.sh"] 
Enter fullscreen mode Exit fullscreen mode
  1. Entrypoint
#!/bin/bash # Start the SSH server service ssh start exec /usr/local/bin/docker-entrypoint.sh mysqld 
Enter fullscreen mode Exit fullscreen mode
  1. Example of docker-compose.yml
services: db-ssh: build: context: . dockerfile: Dockerfile restart: always platform: linux/amd64 ports: - "2222:22" environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: demodb MYSQL_USER: demo 
Enter fullscreen mode Exit fullscreen mode

It's done for coding!

Let's connect

By terminal

# To connect to SSH server ssh root@localhost -p 2222 # Are you sure you want to continue connecting (yes/no/[fingerprint])? yes # Password is what you have set in Dockerfile # After access SSH server, we can connect to MySQL server # Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. # Last login: Sun May 4 10:44:44 2025 from 192.168.228.1 root@4fb7b6bc3e1b:~# mysql -h localhost -u root -p Enter password: root # Then it will show you this Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 13 Server version: 8.0.41 MySQL Community Server - GPL Copyright (c) 2000, 2025, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> 
Enter fullscreen mode Exit fullscreen mode

By GUI app (Sequel Ace)

Use SSH connection on Sequel Ace

MySQL Host is localhost because it uses internal address within container.

Top comments (0)