docker-compose run mysql: ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)

  docker, docker-compose, mysql, mysql5

First off, this is most probably a stupid question that has already been answered a thousand times, but I’m totally roasted after working 14 hours straight, and even after crawling the whole internet I’m unable to find anything of help.

The scene is imaginable simple:

I have a docker-compose.xml with many services required to install and deploy an app, amongst them a simple MySQL 5 service:

    image: mysql:5
    restart: always
      - .mysql:/var/lib/mysql

Now I just want to create the initial database before deploying the app, with a simple:

docker-compose run mysql mysql -e "CREATE DATABASE IF NOT EXISTS database"

But whatever I try I get this error:

Creating network "app_default" with the default driver
Creating app_mysql_run ... done
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
make: *** [database] Error 1

The thing that really bugs me: Even if I first run docker-compose up -d and then run the command, it’s the same output. The only thing that works is entering the container with docker-compose exec mysql /bin/bash and manually executing the exact same command.

What am I missing? Any kind of help is highly appreciated!

Source: Docker Questions