Docker 中的 wp-cli 从 wp-config

问题描述

这是我的 docker-compose.yml 文件

version: '3.9'

services:
  db:
    image: MysqL:5.7
    restart: always
    command: [
        '--disable-partition-engine-check','--default_authentication_plugin=MysqL_native_password','--character-set-server=utf8mb4','--collation-server=utf8mb4_unicode_ci','--max_allowed_packet=100M'
    ]
    volumes:
      - ./db_data:/var/lib/MysqL
    environment:
      MysqL_DATABASE: wordpress
      MysqL_ROOT_PASSWORD: pswd4!


  pma:
    image: PHPmyadmin/PHPmyadmin
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      MysqL_ROOT_PASSWORD: pswd4!
      UPLOAD_LIMIT: 1G
    ports:
      - 8080:80
    depends_on:
      - db

  wp:
    image: wordpress:PHP8.0
    ports:
      - 80:80
    volumes:
      - ./config/PHP.conf.ini:/usr/local/etc/PHP/conf.d/conf.ini
      - ./:/var/www/html
    environment:
      wordpress_DB_HOST: db
      wordpress_DB_NAME: wordpress
      wordpress_DB_USER: root
      wordpress_DB_PASSWORD: pswd4!
      wordpress_DEBUG: 1

    depends_on:
      - db
    links:
      - db:MysqL
    hostname: test.localhost

  wpcli:
    image: wordpress:cli-PHP8.0
    volumes_from:
      - wp
    depends_on:
      - db
      - wp
    links:
      - db:MysqL
    entrypoint: wp
    command: "--info"



volumes:
  db_data:

当我尝试在 Docker 中使用 wp-cli 时(例如 docker-compose run --rm wpcli plugin list),它收到无法连接到数据库错误

Error: `Access denied for user 'username_here'@'192.168.32.5' (using password: YES)`
Error establishing a database connection
This either means that the username and password @R_841_4045@ion in your `wp-config.php` file is incorrect or we can’t contact the database server at `MysqL`. This Could mean your host’s database server is down.

Are you sure you have the correct username and password?
Are you sure you have typed the correct hostname?
Are you sure the database server is running?

If you’re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the wordpress Support Forums. `Access denied for user 'username_here'@'192.168.32.5' (using password: YES)
`

看起来 wp-cli 看到了错误数据库凭据(username_here 而不是 root

执行docker-compose run --rm wpcli config list命令的结果:

enter image description here

可能有什么问题?我在网上找遍了,折腾了几个小时,仍然没有找到问题的原因。

解决方法

您应该为 wpcli 容器指定与 wp 容器中相同的一组环境变量。如果没有,则使用 wordpress 中 php 文件中的默认变量。

请注意:volumes_fromlink 选项在 compose v3 中已弃用。对于链接选项,docker-compose 会自动创建一个网络(或者您可以根据需要指定一个网络),并且嵌入的 docker dns 会根据容器的名称(或组合服务名称)自动将别名分配给您的容器。有关该 here

的更多信息

对于卷,您可以找到更多信息here