|
from fastapi import FastAPI, File, UploadFile, HTTPException |
|
from docker import APIClient |
|
import shutil |
|
import os |
|
|
|
app = FastAPI() |
|
docker_client = APIClient(base_url='unix://var/run/docker.sock') |
|
|
|
@app.post("/build_image/") |
|
async def build_image(file: UploadFile = File(...)): |
|
with open("/tmp/dockerfile", "wb") as buffer: |
|
shutil.copyfileobj(file.file, buffer) |
|
|
|
|
|
try: |
|
response = docker_client.build(path='/tmp', dockerfile='dockerfile') |
|
for line in response: |
|
print(line.decode().strip()) |
|
except Exception as e: |
|
raise HTTPException(status_code=500, detail=f"Error building Docker image: {str(e)}") |
|
|
|
return {"message": "Image built successfully"} |
|
|
|
@app.get("/download_image/") |
|
async def download_image(): |
|
image_name = "myapp_image" |
|
image_tag = "latest" |
|
image_filename = f"{image_name}-{image_tag}.tar" |
|
|
|
|
|
try: |
|
with open(f"/tmp/{image_filename}", "wb") as image_file: |
|
for chunk in docker_client.get_image(image_name, image_tag): |
|
image_file.write(chunk) |
|
except Exception as e: |
|
raise HTTPException(status_code=500, detail=f"Error saving Docker image: {str(e)}") |
|
|
|
return {"filename": image_filename} |
|
|
|
if __name__ == "__main__": |
|
import uvicorn |
|
uvicorn.run(app, host="0.0.0.0", port=8000) |
|
|