无法从cli链接docker容器

8yoxcaq7  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(398)

我尝试使用命令行链接两个docker容器(wordpress和mysql),但没有成功。我也尝试过docker-compose.yml,但只有一个容器在工作,我无法链接两个容器。我使用了以下命令。我目前正在使用aws amazon linux ami。

docker run --name db -e MYSQL_ROOT_PASSWORD=abc123 -p 3306:3306 -d mysql
docker run --name wordpress  --link db:mysql -p 80:80 -d wordpress.

运行这些命令后,只有一个容器(mysql)处于活动状态:

ogsagwnx

ogsagwnx1#

如果你设置一个 docker-compose.yml 在同一网络中有两个容器:

version: '3'
services:
  # Containers
  my_wp_container:
    # ...
    # Container config goes here
    # ...
    networks:
      # Make sure both containers are in the same network
      - my_network_name
    links:
      # "Linking" containers makes it easy to refer to one container from another
      - my_mysql_container

  my_mysql_container:
    # ...
    # Container config goes here
    # ...
    container_name: my_mysql_container
    networks:
      - my_network_name

networks:
  # No additional configuration is required for the network other than
  # creating it; You are of course free to customize it to your needs
  my_network_name:

跑步 docker-compose up 将同时旋转两个容器。你的wordpress容器( my_wp_container )可以轻松访问mysql my_mysql_container 现在是wp容器的主机别名。
一旦两个容器都在运行,就尝试ssh'ing到 my_wp_container 跑步:

ping my_mysql_container

您应该看到,一个容器可以在其docker网络中连接到另一个容器!

相关问题