Python / Uvicorn Fundamentals Interview Questions
How do you run Uvicorn inside a Docker container?
Uvicorn is widely used in containerised deployments. The key considerations are binding to the right host, setting the correct number of workers, and choosing between running Uvicorn directly or via Gunicorn.
# Dockerfile - single-container Uvicorn FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . # Expose the port EXPOSE 8000 # Run Uvicorn - bind 0.0.0.0 so Docker can forward traffic CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4", "--loop", "uvloop", "--http", "httptools", "--log-level", "info", "--no-access-log"] # requirements.txt: # uvicorn[standard] # fastapi
# docker-compose.yml services: api: build: . ports: - "8000:8000" environment: - UVICORN_HOST=0.0.0.0 - UVICORN_PORT=8000 - UVICORN_WORKERS=4 - UVICORN_LOG_LEVEL=info - WEB_CONCURRENCY=4 command: uvicorn main:app # Health check - uvicorn has no built-in health endpoint # Add one to your application: # @app.get("/health") # def health(): return {"status": "ok"}
Key Docker-specific setting: always use --host 0.0.0.0 inside Docker containers. The default 127.0.0.1 binds to the container's loopback interface only, which means Docker's port forwarding cannot reach it - the service will be unreachable from outside the container.
More Related questions...