Home > other >  Why can't I run the mysql command in docker compose?
Why can't I run the mysql command in docker compose?

Time:08-03

I have a project with a mysql database in a container. I use docker-compose to set my project up. And I want to run the mysql command to inspect te database.

So I did, and get:

docker-compose run --rm database mysql
Creating myproject_database_run ... done
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

However when I tried this it works:

docker exec -it myproject_database_1 mysql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Can anybody explain me this?

My docker-compose file:

version: "3.7"

services:
  database:
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    ports:
      - "127.0.0.1:3306:3306"
    env_file: .env
    volumes:
      - type: volume
        source: db_data
        target: /var/lib/mysql
      - type: bind
        source: ./my.cnf
        target: /etc/my.cnf
        read_only: true

volumes:
  db_data:
  testing_images:

CodePudding user response:

docker-compose run creates a new container. That's perfectly normal, but if your mysql client is configured to connect via a Unix socket, the new container will have a new filesystem and won't be able to see the main database container's /var/run directory.

When you use docker-compose run, you need to specify a TCP connection, using the setup described in Networking in Compose in the Docker documentation. For example,

docker-compose run --rm database \
  mysql -h mysql

Since you publish ports: out of the container, you should be able to reach it from the host, without Docker. The trick here is that the mysql command-line client interprets localhost as a magic term to use a Unix socket and not a normal host name, so you need to specifically use the IP address 127.0.0.1 instead.

# From the same host, without anything Docker-specific
mysql -h 127.0.0.1

CodePudding user response:

Try adding MYSQL_ROOT_PASSWORD in the environment.

environment:
    MYSQL_ROOT_PASSWORD: root

This is from one of my working compose file

services:
    ## -----------------------------------------------
    ##           MySql database
    ## -----------------------------------------------
    db_mysql:
      image: mysql:8.0
      restart: always
      volumes:
        - db_mysql:/var/lib/mysql
        - ./mysql:/docker-entrypoint-initdb.d
      command: --default-authentication-plugin=mysql_native_password
      environment:
        MYSQL_ROOT_PASSWORD: root
      networks:
        - app-network
      deploy:
        mode: global
      ports:
        - "3306:3306"

    ## map volume
    volumes:
      db_mysql:

    ## in network, we can define any name under networks:
    networks:
       app-network:
        driver: bridge

FYI: Official MySQL docker image - Docker Hub

  • Related