onthego / app2.py
Azeez98's picture
Rename app.py to app2.py
b7c95da verified
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)