简体   繁体   English

连接到docker里面的mysql

[英]Connect to mysql inside docker

I'm using the official MySQL image from docker hub and expose ports 3333:3306 to connect from outside. 我正在使用来自docker hub的官方MySQL映像并公开端口3333:3306以从外部连接。

I know that I have to change the bind IP inside /etc/mysql/my.cnf to the IP of this container and grant permission for a user like: GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'container_ip'; 我知道我必须将/etc/mysql/my.cnf的绑定IP更改为此容器的IP,并为用户授予以下权限: GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'container_ip'; GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'container_ip'; so I can connect to this container by: 所以我可以通过以下方式连接到此容器:

mysql -h container_ip -u root -p

But I received this error 但是我收到了这个错误

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Btw, I also try to connect from WordPress in another container but it cannot establish the connection. 顺便说一句,我也尝试从另一个容器中的WordPress连接,但它无法建立连接。 Here is docker-compose.yml 这是docker-compose.yml

version: '2'
services:
  mysqldb:
    image: mysql:5.6
    environment:
      MYSQL_ROOT_PASSWORD: password
    volumes:
      - ./mysql-data:/var/lib/mysql
      - ./mysql-import-data:/import-data
    ports:
      - "3333:3306"
  blog:
    image: webdevops/php-nginx:ubuntu-14.04
    environment:
      WEB_DOCUMENT_ROOT: /usr/share/nginx/html
    volumes:
      - ./blog:/usr/share/nginx/html
    ports:
      - "8080:80"
    depends_on:
      - mysqldb
  1. What's the mistake I made with this mysql container? 我用这个mysql容器犯了什么错误? I cannot connect to it. 我无法连接到它。
  2. The IP of the container may change every time docker-compose up . 每次docker-compose up ,容器的IP都可能会发生变化。 How can I configure it? 我该如何配置?

Hmm I'm a little confused. 嗯,我有点困惑。 From the point of view of the host os, the docker container is bound to one or more network interfaces. 从主机操作系统的角度来看,docker容器绑定到一个或多个网络接口。 In your compose file you are exposing port 3333 to the host. 在您的撰写文件中,您将端口3333暴露给主机。 That's what you have to connect to. 这就是你必须连接的东西。

Plus you need to use an IP address, otherwise the mysql client will try to connect with a unix socket. 另外,您需要使用IP地址,否则mysql客户端将尝试连接unix套接字。

mysql -h 127.0.0.1 --port 3333 -u root -p

If you are trying to connect from inside your blog container then you can use mysqldb as your host with the 3306 port. 如果您尝试从博客容器内部进行连接,则可以使用mysqldb作为3306端口的主机。

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

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