在 mysql docker 中增加 max_allowed_packet 大小

increase max_allowed_packet size in mysql docker

我们正在使用 Docker 作为 mysql,我们在 运行

时遇到以下错误
Packet for query is too large (12884616 > 4194304). You can change this value on the server by setting the max_allowed_packet' variable.; nested exception is com.mysql.jdbc.PacketTooBigException: Packet for query is too large (12884616 > 4194304). You can change this value on the server by setting the max_allowed_packet' variable.

现在我们需要在 mysql 配置中增加 max_allowed_packet 大小,任何人都可以在 docker 命令上帮助我增加 max_allowed_packet.

我认为你应该像这样在你的 Dockerfile 中修改它:

RUN sed -ire 's/max_allowed_packet.*=.*/max_allowed_packet = YOURVALUE/g' /etc/mysql/my.cnf

作为容器命令的参数:

docker run -it -e MYSQL_ROOT_PASSWORD=my-secret-pw mysql:5.7 --max-allowed-packet=67108864

参见 https://hub.docker.com/_/mysql/ 中的 "Configuration without a cnf file",为后代复制此处:

Configuration without a cnf file Many configuration options can be passed as flags to mysqld. This will give you the flexibility to customize the container without needing a cnf file. For example, if you want to change the default encoding and collation for all tables to use UTF-8 (utf8mb4) just run the following:

$ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci

If you would like to see a complete list of available options, just run:

$ docker run -it --rm mysql:tag --verbose --help

使用 docker-compose 时(如评论中所问),添加一个带有参数的 command 键:

version: "3"
services:
  data:
    image: "mysql:5.7.20"
    command: --max_allowed_packet=32505856      # Set max_allowed_packet to 256M (or any other value)
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=db
      - MYSQL_USER=user
      - MYSQL_PASSWORD=user_password

使用 docker-compose 时(如评论中所问),添加带有参数的 command 键,例如:

version: "3"
services:
  data:
    image: "mysql:5.7.20"
    # Set max_allowed_packet to 256M (or any other value)
    command: --max_allowed_packet=32505856
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=db
      - MYSQL_USER=user
      - MYSQL_PASSWORD=user_password

虽然这适用于 MySQL docker 图像,但它可能不适用于所有图像,因为它会覆盖默认命令。

更多信息:Docker Compose - Command