JPcode
JPcode

Reputation: 90

How to load csv into mysql with docker-compose?

I want to load a csv into my mysql container.

This is my docker-compose:

version: '3.7'

services: 
  db:
    image: mysql
    ports:
      - 3306:3306
    environment: 
      - MYSQL_ROOT_PASSWORD=root123
      - MYSQL_DATABASE=test
      - MYSQL_USER=test
      - MYSQL_PASSWORD=test123
    volumes:
      - './init.sql:/docker-entrypoint-initdb.d/init.sql'
      - './init_data:/docker-entrypoint-initdb.d/init_data'

It does create the table, but it doesn't load the csv into the table.

As far as I have researched I have to pass this as an argument to mysql image, but I dont know how to add an argument by docker-compose.

--secure-file-priv=docker-entrypoint-initdb.d

This is what I am following.

But I don't want to use docker run.

Any help or tips are welcomed.

Upvotes: 3

Views: 728

Answers (1)

peterh
peterh

Reputation: 1

You can not add an argument to the docker compose for building, because docker compose can not build images. More clearly it can, by calling a docker build (using the info you gave in docker-compose.yml), but the things what you call on building the image can be defined only in the Dockerfile. You can not give commands in the docker-compose.yml for building.

What you can do: you can use the mysql image as a base to create your own image - with its own Dockerfile. Roughly so:

services:
  mymysql:
    build:
      context: ./mymysql
    ...other things in your docker compose...

That will define a new container named mymysql, whose definition is in the ./mymysql directory. Create this directory and then put a Dockerfile into it. This Dockerfile should look like

FROM mysql:latest
USER mysql
RUN ...
RUN ...

In the RUN lines you can define the commands, what will be executed - on the pulled mysql:latest image and generate mymysql for you.


Alternative option: start the container and load the csv by running it. Then stop the container. After that a docker commit fce2ea31 mymysql will save the stopped container as a new image, in the name what you want. This is easier but much lesser reproducible, so I suggest to do the first.

Upvotes: 1

Related Questions