简体   繁体   中英

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

I'm tring to make a docker with mysql and apache php.

I want to easly connect the mysql inside my php code without having to search the current ip of the mysql container.

How i could link the mysql ip adress in my php-apache container?

My docker-compose file:

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:

$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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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