Ad

Why Can't I Run The Mysql Command In Docker Compose?

- 1 answer

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:
Ad

Answer

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 database

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
Ad
source: stackoverflow.com
Ad