2017-05-26 25 views
1

我使用docker在容器中啓動mysql服務。容器啓動後,我想通過python腳本自動插入一些數據到數據庫。這是我的Dockerfile在docker容器中啓動mysql後插入數據

FROM mysql:5.7 

EXPOSE 3306 

ENV MYSQL_ROOT_PASSWORD 123456 

WORKDIR /app 
ADD . /app 

RUN apt-get update \ 
    && apt-get install -y python3 \ 
    && apt-get install -y python3-pip 
RUN pip3 install --user -r requirements.txt 
RUN python3 init.py 

最後一行運行腳本的一些數據添加到數據庫,但因此它運行docker build失敗時這段時間mysql服務尚未啓動。我該如何做到這一點?提前致謝。

回答

1

According to the docs,MySQL的入口點會自動執行任何文件與/docker-entrypoint-initdb.d發現.sh.gz.sql腳本。所以,創建一個腳本來爲你執行你的Python腳本。如果你把這個文件01-my-script.sh,您Dockerfile看起來就像這樣:

FROM mysql:5.7 

EXPOSE 3306 
ENV MYSQL_ROOT_PASSWORD 123456 
WORKDIR /app 

RUN apt-get update && apt-get install -y \ 
    python3 \ 
    python3-pip 

# Copy requirements in first, and run them (so cache won't be invalidated) 
COPY ./requirements.txt ./requirements.txt 
RUN pip3 install --user -r requirements.txt 

# Copy SQL Fixture 
COPY ./01-my-script.sh /docker-entrypoint-initdb.d/01-my-script.sh 
RUN chmod +x /docker-entrypoint-initdb.d/01-my-script.sh 

# Copy the rest of your project 
COPY . . 

而且你的腳本將只包含:

#!/bin/sh 

python3 /app/init.py 

現在,當你把你的容器,你的腳本將被執行。使用docker logs -f <container_name>監控正在運行的容器的執行情況,以確保腳本正在運行。

+0

謝謝。它解決了我的問題! –