简体   繁体   English

Docker,如何在 PHP 的另一个容器中获取容器 IP?

[英]Docker, How to get a container IP inside another container in PHP?

I'm tring to make a docker with mysql and apache php.我正在尝试用 mysql 和 apache ZE1BFD762321E409CEE4AC0BE6 制作 docker

I want to easly connect the mysql inside my php code without having to search the current ip of the mysql container.我想在我的 php 代码中轻松连接 mysql,而无需搜索 Z8157B527BCFBAD2E80F58D20683931435Z 容器的当前 ip。

How i could link the mysql ip adress in my php-apache container?我如何在我的 php-apache 容器中链接 mysql ip 地址?

My docker-compose file:我的docker-compose文件:

version: "3.2"

services:
  apache:
    build:
      context: './docker/apache/'
    links:
      - mysql:mysqldb
    depends_on:
      - mysql
    ports:
      - "80:80"
    volumes:
      - ./:/var/www/html/
      - ./docker/apache/virtualhost.conf:/etc/apache2/sites-enabled/000-default.conf
      - ./docker/apache/php.ini:/usr/local/etc/php/php.ini
    container_name: apache

  mysql:
    image: mysql/mysql-server:8.0
    command: ['--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci','--default-authentication-plugin=mysql_native_password']
    restart: always
    ports:
      - "18906:3306"
    # volumes:
    #   - ./docker/mysql-dump:/docker-entrypoint-initdb.d

    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: dbtest
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      MYSQL_ROOT_HOST: '%'
    container_name: mysql

My php script:我的 php 脚本:

$conn = mysqli_connect(
  '172.10.0.2', // i want this to change acording to the mysql container
  $user,
  $pass,
  $database
);

If you need something else please let me know.如果您需要其他东西,请告诉我。

Try this:尝试这个:

$conn = mysqli_connect(
  'mysql', // here goes your mysql container name
  $user,
  $pass,
  $database
);

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

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