如何使用Docker容器设置MySQL主机限制

时间:2019-04-26 08:55:52

标签: docker

我正在将 mysql:5 容器(来自docker hub的图像)设置到与另一个容器(Web服务器)共享的子网中。

我想将我的mysql用户限制为与Web服务器容器相对应的主机。

如果我直接通过Web服务器容器ip对其进行限制,则它可以工作,但是由于docker环境,该ip无法更改,所以我想使用以下类似的东西:

GRANT ALL PRIVILEGES ON `db`.* TO 'user'@'container-name'

当我尝试连接服务器时响应:

  

拒绝访问用户'user'@'172.18.0.4'

其中172.18.0.4是Web服务器容器的正确IP。


示例:

docker-compose.yaml

version: '2'
services:
  mysql1:
    image: mysql
    container_name: mysql1
    ports:
      - '3306:3306'
    environment:
      - MYSQL_ROOT_PASSWORD=rootpwd

  mysql2:
    image: mysql
    container_name: mysql2
    environment:
      - MYSQL_ROOT_PASSWORD=rootpwd

上集装箱

docker-compose up -d

将用户创建到mysql1

docker-compose exec mysql1 mysql -u root --password="rootpwd" -e "CREATE USER user@mysql2 IDENTIFIED BY 'pwd'; GRANT ALL PRIVILEGES ON * TO user@mysql2" sys

尝试由用户从mysql2访问mysql1

docker-compose exec mysql2 mysql -u user --password="pwd" -h mysql1 sys
  

错误1045(28000):用户'user'@'172.18.0.3'的访问被拒绝(使用密码:是)

Docker网络信息

docker network inspect test-mysql-user-host_default    
{
    "Name": "test-mysql-user-host_default",
    "Id": "305f4da33e0b79d899ac289e6b3fc1ebf2733baf0bf3d60a53cc94cec44176d1",
    "Created": "2019-04-26T09:53:23.3237197Z",
    "Scope": "local",
    "Driver": "bridge",
    "EnableIPv6": false,
    "IPAM": {
        "Driver": "default",
        "Options": null,
        "Config": [
            {
                "Subnet": "172.18.0.0/16",
                "Gateway": "172.18.0.1"
            }
        ]
    },
    "Internal": false,
    "Attachable": false,
    "Ingress": false,
    "ConfigFrom": {
        "Network": ""
    },
    "ConfigOnly": false,
    "Containers": {
        "133ebd1e6ba485212e5448670c66c1718917650bc217264183c725fb1a928118": {
            "Name": "mysql1",
            "EndpointID": "ce89aa1674e9c46fad50b2f36aec8d1eecf2227f597a785be67785ade770fef7",
            "MacAddress": "02:42:ac:12:00:02",
            "IPv4Address": "172.18.0.2/16",
            "IPv6Address": ""
        },
        "d67072a5c486752b7018fa321e47ae09fb873199604c2b520f2305968d43b577": {
            "Name": "mysql2",
            "EndpointID": "e6b62c6ce9e266d38be383fa6029f378e1ca67a18420dd3f508a3089200c0d98",
            "MacAddress": "02:42:ac:12:00:03",
            "IPv4Address": "172.18.0.3/16",
            "IPv6Address": ""
        }
    },
    "Options": {},
    "Labels": {}
}

1 个答案:

答案 0 :(得分:0)

贝拉肯的评论

  

这似乎是MySQL的skip-resolve-host选项的问题,该选项当前已硬编码在Dockerfile中(请参阅此GitHub问题)。 TLDR:您可以基于mysql:5创建自己的映像,然后取消此选项,或者使用%通配符代替mysql2。

他就在official dockerfile for mysql:5.7,在第70行,我们可以找到:

#don't reverse lookup hostnames, they are usually another container
&& echo '[mysqld]\nskip-host-cache\nskip-name-resolve' > /etc/mysql/conf.d/docker.cnf

我做了一个新的Dockerfile,删除了此配置文件。

FROM mysql:5.7

RUN rm /etc/mysql/conf.d/docker.cnf

EXPOSE 3306 33060
CMD ["mysqld"]