繁体   English   中英

使用 mysql 命令从一个 docker 容器到另一个

[英]Using the mysql commands from one docker container to another

我在 docker 中创建了一个网络,并将两个 docker 容器连接到同一个网络。 一个容器是应用程序容器,另一个是数据库容器。 我检查了两个容器之间是否发生了 ping,它是成功的。 现在,如何从应用程序容器运行 MySQL 命令?

Mysql的容器Ip是172.17.0.3 Application的容器Ip是172.17.0.2

如果您使用多个容器,我建议使用一些工具来组织它们,例如 Docker Compose、Docker Swarm、Kubernetes 等容器。

例如,您在 DockerCompose 上的堆栈如下:

version: "3"

services:

  mysql:
    image: mysql:latest
    environment:
      MYSQL_DATABASE: 'db'
      # So you don't have to use root, but you can if you like
      MYSQL_USER: 'user'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'password'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'password'
    volumes:
      - my-db:/var/lib/mysql

  app:
    # Use ./ as Docker Build context path
    build: .
    environment:
      MYSQL_DATABASE: 'db'
      # So you don't have to use root, but you can if you like
      MYSQL_USER: 'user'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'password'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'password'

# Names our volume
volumes:
  my-db:

您甚至可以将数据库连接参数移动到.env并使用上面 YAML 中的值。

在此示例中,名为app的容器可以使用mysql主机名访问 MySQL 数据库。 它将自动填充到容器/etc/hosts中。

暂无
暂无

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

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