簡體   English   中英

動態構建時如何將文件復制到 docker 映像

[英]How do I copy a file to docker image when building dynamically

我想使用 Python/docker-py 動態構建 docker 圖像。 我的示例代碼如下所示。 問題是我在 COPY 命令中遇到了構建上下文錯誤之外的禁止路徑 我不知道在哪里放置我的 build.sql (sql_build_path} 文件以避免在動態情況下發生這種情況。

docker_file = f"""
    FROM postgres
    ENV POSTGRES_USER myuser
    ENV POSTGRES_PASSWORD mypassword
    ENV POSTGRES_DB mydb
    ENV ON_ERROR_STOP 1
    COPY {sql_build_path} /docker-entrypoint-initdb.d/
"""
f = io.BytesIO(docker_file.encode('utf-8'))
client = docker.from_env()
client.images.build(fileobj=f, tag="test", rm=True)

[編輯]
謝謝,Jeevan - 我能夠發現這是一個已知(並且有些爭議)的問題,僅限於安全影響。 動態構建 docker 文件並將資源復制到目錄似乎是最好的響應。 對於我的解決方案,我選擇了python的臨時目錄API。

with tempfile.TemporaryDirectory() as temp_dir:
    # save docker file to this directory
    # copy other files to this directory
    name, updates = client.images.build(path=temp_dir, dockerfile='Dockerfile', tag="test")
    for u in updates:
        print(u)

默認情況下, fileobj在沒有任何構建上下文的情況下發送Dockerfile ,這就是您無法復制任何內容的原因。

這是我的方法:

創建 Dockerfile 並在 Dockerfile 的目錄中復制build.sql

構建-img.py

import docker
path = '/root/Test/'  # Where Dockerfile and build.sql resides
client = docker.from_env()
print("Building image")
client.images.build(path=path, dockerfile='Dockerfile',tag="test-image")

Dockerfile

FROM postgres
ENV POSTGRES_USER myuser
ENV POSTGRES_PASSWORD mypassword
ENV POSTGRES_DB mydb
ENV ON_ERROR_STOP 1
COPY build.sql /docker-entrypoint-initdb.d/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM