Docker 中的 wp-cli 从 wp-config 获取错误的数据库登录凭据

wp-cli in Docker fetches wrong database login credentials from 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 information 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命令的结果:

有什么问题吗?我在网上找遍了,找了好几个小时都没找到问题的原因。

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

请注意:volumes_fromlink 选项在 compose v3 中已弃用。对于 link 选项,docker-compose 会自动创建一个网络(或者您可以根据需要指定一个网络)并且嵌入 docker dns 会根据容器的名称自动将别名归因于您的容器(或组成服务名称)。更多信息 here

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