Yabo Lee
Yabo Lee

Reputation: 21

Dockerfile create image with both python and mysql

I have two containers "web" and "db". I have an existing data file in csv format.

The problem is I can initialize the MySQL database with a schema using docker-compose or just run with parameters but how can I import the existing data? I have Python script to parse and filter the data and then insert it to db but I cannot run it in the "db" container due to the single image is MySQL.

Update1

version: '3'
services:
  web:
    container_name: web
    build: .
    restart: always
    links:
      - db
    ports:
      - "5000:5000"
  db:
    image: mysql
    container_name: db
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_DATABASE: "test"
      MYSQL_USER: "test"
      MYSQL_PASSWORD: "test"
      MYSQL_ROOT_PASSWORD: "root"
      MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
    ports:
      - "33061:3306"

There is a Python script for read data from a csv file and insert them to database, which works fine. Now I want to running the script once the MySQL container is set up. (I have done connection with Python and MySQL in container)

Otherwise, anyone has a better solution to import existing data?

Upvotes: 1

Views: 3158

Answers (2)

Mostafa Hussein
Mostafa Hussein

Reputation: 11940

MySQL docker image has the ability to execute shell scripts or sql files if these script/sql files mounted under /docker-entrypoint-initdb.d for a running container as described in here and here. So I suggest you to write an SQL file that reads the CSV file (which you should mount to your container so the sql file can read it) in order to restore it to MySQL maybe something similar to this answer or write a bash script to import csv into mysql whatever works for you.

You can check Initializing a fresh instance at the official dockerhub page for mysql

Upvotes: 2

heyitsvajid
heyitsvajid

Reputation: 1121

From Dockerfile, you can call a script (Entrypoint). In this script you can call your python script. For example:

DockerFile:

FROM php:7.2-apache

RUN apt-get update    
COPY ./entrypoint.sh /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]

This will run your entrypoint script in the App container. Make sure you've depends on attribute in you app container compose description.

Upvotes: 0

Related Questions