File size: 1,440 Bytes
320bc20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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)

    # Build Docker image
    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"  # Replace with your image name
    image_tag = "latest"  # Replace with your image tag
    image_filename = f"{image_name}-{image_tag}.tar"

    # Save Docker image as a tar file
    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)