Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to a MySQL Docker Container via SSH?

When I try to tunnel via SSH to the Host Mashine (vServer) and then try to connect via the internal docker Container-IP then I can't connect to MySQL.

This is my docker-compose file.

version: '2'
services:
  mysql:
    build: ./mysql
    environment:
      MYSQL_ROOT_PASSWORD: test
    volumes:
      - ./db:/var/lib/mysql

The only solution I found was to forward the MySQL-Port of the mysql container to the Host-Mashine.

version: '2'
services:
  mysql:
    build: ./mysql
    environment:
      MYSQL_ROOT_PASSWORD: test
    volumes:
      - ./db:/var/lib/mysql
   ports:
     - 3306:3306

Then I am able to connect via the Host IP to MySQL but this is without SSH its direct via TCP and the port. This is a No-Go for me to bring the MySQL Service into the internet.

Reasons can be found here https://security.stackexchange.com/questions/63881/is-it-not-safe-to-open-mysqls-port-to-the-internet why it is not a good practice to bring your mysql port into the internet.


So what is a good practice to connect to my docker mysql container with SSH but keep the mysql ports closed?

like image 960
TatzyXY Avatar asked Feb 12 '17 12:02

TatzyXY


People also ask

How do I connect to a MySQL docker container?

Here are the steps you can follow to install the Dockerhub MySQL Container: Step 1: Pull the Docker Image for MySQL. Step 2: Deploy and Start the MySQL Container. Step 3: Connect with the Docker MySQL Container.

Can you ssh into a docker container?

The SSH method works fine for Docker containers, too. That said, you can SSH into a Docker container using Docker's built-in docker exec . If you do not need an interactive shell, you can also use the docker attach command to connect the host's stdin and stdout to the running container and execute remote commands.

How do I connect to a docker container?

Use docker attach to attach your terminal's standard input, output, and error (or any combination of the three) to a running container using the container's ID or name. This allows you to view its ongoing output or to control it interactively, as though the commands were running directly in your terminal.


1 Answers

One simple way is to bind the MySQL port only to the localhost address. That assumes the host has a mysql client available outside of Docker.

ports:
  - 127.0.0.1:3306:3306

You could also omit the ports section completely (no port binding at all), and use the mysql client that's already inside the container.

docker-compose exec mysql bash

Then run the mysql command inside the container to do whatever queries you want to do.

like image 127
Dan Lowe Avatar answered Sep 24 '22 09:09

Dan Lowe