Home  >  Q&A  >  body text

How to enable remote access to mysql docker's root user in docker-compose file?

Currently, I am using the following simple YAML file to start a MySQL server

version: '3.3'
services:
  db:
    image: mysql/mysql-server
    restart: always
    environment:
      MYSQL_DATABASE: 'db'
      MYSQL_USER: 'user'
      MYSQL_PASSWORD: 'strongpasswordnobodycanguessorcrackatall'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'somethingevenmorestrongerthaneverbefore'
    ports:
      - '3306:3306'
    expose:
      - '3306'
    volumes:
      - compose-my-db
volumes:
  - ./:compose-my-db:

However, I have to connect to the container and use the following command:

Grant 'c'@'%';refresh permission to all content on *.*;

This gives me all the permissions I need and allows remote connections through the user created in the compose file.

I know I can modify the my.cnf file or add an init script that runs after mysqld is initialized, but I want the user created in Docker-Compose.

P粉145543872P粉145543872382 days ago567

reply all(1)I'll reply

  • P粉144705065

    P粉1447050652023-09-07 10:38:13

    I think we can achieve this by MYSQL_INITDB - setting up an init script in the MySQL container.

    First, you can add an environment variable for MYSQL_INITDB like below

    MYSQL_INITDB: /docker-entrypoint-initdb.d/01.sql

    Then you need to update the volume configuration as follows

    volumes:
      - ./compose-my-db:/docker-entrypoint-initdb.d

    Create a 01.sql file in the same directory as your docker-compose file.

    GRANT ALL ON *.* TO 'c'@'%';
    FLUSH PRIVILEGES;

    View the official documentation here: https://hub.docker.com/_/mysql/ Under the Initializing a fresh instance subtopic.

    reply
    0
  • Cancelreply