Timmy
Timmy

Reputation: 745

Running custom SQL query after docker container is built

What I want to do:

What I've done:

  1. I've created a docker-compose.yml file where I describe my service and for each component, I've created a dockerfile inserting the command to run. I obtain the shown error.
  2. I've added some sleep second. Nothing changed
  3. I've tried to create a second service depending on the database and run from there the queries. Nothing changed, still the same error.

Where is the problem?

I cannot execute any command until every service is built and running. In the following dockerfile:

FROM mariadb:latest
ARG MYSQL_ROOT_PASSWORD
RUN mysql -uroot -p${MYSQL_ROOT_PASSWORD} -e "CREATE DATABASE test"

I get the following error:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Here is the docker-compose.yml file:

version: '3.1'

services:

  db:
    image: mariadb:latest
    build: 
      context: ./db
      args:
        MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD}"
    container_name: IUB_sql
    restart: unless-stopped
    environment:
       MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD}"
        MYSQL_DATABASE: "useless_test_db"
        MYSQL_USER: "${MYSQL_USER}"
        MYSQL_PASSWORD: "${MYSQL_PASSWORD}"
    ports:
      - ${MYSQL_PORT}:3306

Note:

I do not want to create only a database, I want to run some arbitrary queries.

Note 2:

If I delete the RUN mysql ... line the service goes up. Then if I try to run the following command I'm able to run successfully the query: docker exec -umysql -it IUB_sql mysql -uroot -p -e "CREATE DATABASE test_cmdline"

Upvotes: 0

Views: 1781

Answers (1)

Diego Dupin
Diego Dupin

Reputation: 1348

See "Initializing a fresh instance" in https://hub.docker.com/_/mariadb. You can add a folder with SQL files that will be run ONCE only. that can be done with docker-compose adding this configuration:

volumes:
  - /your-directory-with-sql-files:/docker-entrypoint-initdb.d

see https://github.com/docker-library/mariadb/blob/2345e98dc89edae8f11c35ad838887f45859de75/10.4/docker-entrypoint.sh#L314 for detail.

Upvotes: 3

Related Questions