簡體   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