By Bernat Sampera 2 min read Follow:

Deploy python backend with docker

How to build an image and deploy it via docker using pyproject.toml and fastapi.

Setup

main.py

Te entrypoint for the app will be a main.py file . It will include the setup of fastapi. For this example we’ll also use pyproject.toml, you can see more details about it here

# Example main.py
app = FastAPI(
    title="TranslatePrompt",
    description="Translateprompt is a site that allows users to translate with a glossary",
    version="1.0.0",
)

# Add CORS middleware before defining routes
app.add_middleware(
...
)

@app.get("/health")
def read_root():
    """Health check endpoint."""
    return {"status": "ok"}

# Include routers
app.include_router(...)

if __name__ == "__main__":
    uvicorn.run(
        "main:app", host=config.API_HOST, port=config.API_PORT, reload=config.API_RELOAD
    )

Dockerfile

On the root of the project create a Dockerfile with the following configuration

FROM python:3.12-slim

# Set working directory
WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# Copy pyproject.toml first for better caching
COPY pyproject.toml ./

# Install Python dependencies
RUN pip install --no-cache-dir -e .

# Copy the entire backend application
COPY . .

# Expose the port
EXPOSE 8008

# Set environment variables
ENV API_HOST=0.0.0.0
ENV API_PORT=8008
ENV API_RELOAD=false
ENV PYTHONPATH=/app

# Command to run the application
CMD ["python", "main.py"]

Test the app locally

You can build the image by running

docker build -t <your-app_name> .

And create the container locally by

docker run -p 8008:8008 \
  -e PROD=TRUE \ # Here you can add your env variables
  <your-app_name>

Now if you test your app on localhost:8008 , it should be running

@app.get("/health")
def health_check():
    """Health check endpoint."""
    return {"status": "ok"}

# after visiting localhost:8008/health, you should see that status ok

Deploy to coolify

Select to add new resource —> load from github and choose Dockerfile, now the resource will be created and you’ll see the configuration settings of the resource.

  • Base directory, if the project is not on the root directory. (Ex: /backend)

  • Ports Exposes, the port where the service will run (Ex: 8008)

  • Env variables (On the left tab)

  • Optional: name of the resource