简体   繁体   English

如何通过SSH连接到MySQL Docker容器?

[英]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. 当我尝试通过SSH隧道连接到Host Mashine(vServer)然后尝试通过内部docker Container-IP连接时,我无法连接到MySQL。

This is my docker-compose file. 这是我的docker-compose文件。

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. 我找到的唯一解决方案是将mysql容器的MySQL-Port转发给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. 然后我可以通过主机IP连接到MySQL,但这是没有SSH直接通过TCP和端口。 This is a No-Go for me to bring the MySQL Service into the internet. 对于我来说,将MySQL服务引入互联网是一种禁忌。

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. 原因可以在这里找到https://security.stackexchange.com/questions/63881/is-it-not-safe-to-open-mysqls-port-to-the-internet为什么带上你的不是一个好习惯mysql端口进入互联网。


So what is a good practice to connect to my docker mysql container with SSH but keep the mysql ports closed? 那么用SSH连接我的docker mysql容器但是保持mysql端口关闭是一个好习惯呢?

One simple way is to bind the MySQL port only to the localhost address. 一种简单的方法是仅将MySQL端口绑定到localhost地址。 That assumes the host has a mysql client available outside of Docker. 假设主机在Docker之外有一个mysql客户端。

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. 您也可以完全省略ports部分(根本没有端口绑定),并使用已经在容器内的mysql客户端。

docker-compose exec mysql bash

Then run the mysql command inside the container to do whatever queries you want to do. 然后在容器内运行mysql命令来执行您想要执行的任何查询。

An easy way to achieve this is to forward the ssh port of the docker conatiner to some port on your host, ie 实现此目的的一种简单方法是将docker conatiner的ssh端口转发到主机上的某个端口,即

ports:
   - 22:<some free host port>

and then access the container via ssh to the host port you used. 然后通过ssh访问容器到您使用的主机端口。 Note, that it is a bad idea to use port 22, since that will cause a conflict with the ssh server running on your host. 请注意,使用端口22是个坏主意,因为这会导致与主机上运行的ssh服务器发生冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM